Category Archives: Incident Handling and Hacker Techniques

Security Hands-On-Training – Part 4

[Following part 3 where the  ASP.NET web site code was modified, part 4 will show different methods, techniques, and ways of manipulating the user input in order to control the logic of the application making the web application exploitable. ~Luis]

During the previous chapter the defenses that were in place in the test application were removed. To achieve this a  trial and error approach was used. While looking for SQL injection vulnerabilities, different methods, techniques, and ways of manipulating the user input were tried in order to see how the system reacted. This method allows us to learn and practice which defenses would need to be removed to allow a successful exploit.

The HelpDesk.aspx page is shown in the next figure. It simulates a helpdesk ticketing system where the user is allowed to input data into two fields. The “Station Number” and the “Problem Description”.

security-hot-fig9

When the user clicks on the “Submit Request” button, the web form takes the value and passes it to a SQL statement. This will happen without validation controls because they were removed in the previous post. Behind the scenes this page contains an INSERT SQL statement that will receive the user input and insert it into the database. The code block that allows this to happen is shown below.

security-hot-fig10

The database called “Dorknozzle” contains a table called “HelpDesk”. This is shown in the below figure. In the database there are several columns that are used to store the user input. During the trial and error method to discover a SQL injection point  it was found that input that is stored in the database as an integer could not be manipulated.  This applies to the “Station Number” field. However, the “Description” field uses the nvarchar type and allows up to 50 characters to be inserted.

security-hot-fig11

With this in mind and with the defenses down the reader can start adding characters in the user input fields that would change the initial query logic and see how the system reacts. The first character to try is the single quote. When clicking the submit button the web application returns a SQL exception message. This happens because the error messages were enabled.

security-hot-fig12

This was exactly the objective. This SQL error message discloses that the statement submitted had an unmatched number of single quote characters. To further exploit it the reader would need a way to construct a statement in the input field that allowed to terminate the string and append the malicious SQL statement (OWASP,4). At this stage the debug functionality of Visual Studio Express was used. By introducing a break point in the code where the SQL statement is, the application execution could be controlled. Then the Web application was started in debug mode. In the HelpDesk page the character “A” and a single quote was inserted in the “Problem Description” field. When submitting the request the break point kicked in and the step into functionality was used to dig into what was happening. This allows us to verify exactly how the SQL statement was being constructed and executed by the database. The next figure shows these steps.

security-hot-fig13

The SQL statement that was being sent to the database was not well formed due to the crafted input which caused an odd number of single quote characters resulting in a SQL error. The below figure shows what the SQL statement looks like.

security-hot-fig14

Now it is just a manner of time to find the correct input that will create a well formed SQL statement and introduce the malicious SQL code. During this iterative process the reader can find that he could close the SQL statement by injecting the right number of values that the database is expecting. Then another statement could be inserted and this would be the injection point and the “–“ sequence (two dashes) can be used to ignore the rest of the statement. This SQL injection point is inside an INSERT statement. Because of this you couldn’t see the output of the injected query or any difference in the in the responses of the web application which increases the difficulty of the technique. Using a technique called Blind SQL injection, which was first introduced by Chris Anley in 2002, the reader  might use inference techniques to get the results (Clarke, 2012). For example, with this technique, SQL statements that analyze the response time can be used. One method is using the sleep function like WAITFOR DELAY ‘time’. Using this technique the reader could make the database wait and reveal if a statement was true or false. In the next figure is shown how the SQL statement would look like after having the evil payload inserted. This will result in the database to wait 5 seconds before producing the results.

security-hot-fig15

In addition to the previous example the following SQL statements could be used in the SQL injection point to understand how the database would react:

IF (1=1) WAIT FOR DELAY ‘0:0:5’ —
IF (1>2) WAIT FOR DELAY ‘0:0:5’ —

Then more advanced queries could be used to determine if the current user is part of the sysadmin role:

IF((SELECT (CASE WHEN (IS_SRVROLEMEMBER(‘sysadmin’)=1) THEN ‘1’ ELSE ‘0’ END))=’1′) WAITFOR DELAY ‘0:0:5′ –

This seems a rather tedious and slow process but this will be automated using well known SQL injection tools in the upcoming articles. These tools dramatically increase the efficiency of an attacker but also extend the attack population. One disadvantage of these powerful tools is that any inexperienced person can mount complex SQL injection attacks regardless the technique or the database technology (Clarke, 2012).

During this exercise the reader is able to learn about SQL, its inner working queries and how SQL statements are constructed. It should be clear now why is important to disable any error messages and  why it is important to sanitize all input. When the reader has a good understanding of the tools and techniques and can control the logic of the application the reader could also use SQL injection with serious consequences. Tools like SQLmap and SQLninja can be used to automate these techniques.

Even though the focus was on SQL injection the environment is ready for additional tests by reducing our defenses further. In the context of this web application the reader could introduce other vulnerabilities such as Cross-Site scripting (XSS), Cross-Site Request Forgery (CSRF) or introduce a broken authentication mechanism. Learning how to do this and understanding the mechanisms behind the scenes is a rewarding exercising. Likewise, learning the attack vectors, use the tools, taking the time to experiment with them and understand how they work will make one better equipped and skilled.

 

References:
OWASP. (4, September 13). Testing for sql injection (owasp-dv-005). Retrieved from https://www.owasp.org/index.php/Testing_for_SQL_Injection_(OWASP-DV-005)
Clarke, J. (2012). Sql injection attacks and defense, 2nd edition. Syngress.

Tagged , , , ,

Security Hands-On-Training – Part 3

[Following part 1 and part 2 where we built an infrastructure with different systems, below article will focus on the Web Stack and will show how the ASP.NET code has been modified in order to make the application less secure. This will allow us to understand the security mechanism enforced by the application in order to make it defenseless and practice our security tools and techniques! ~Luis]

Instead of modifying the secure test application, the reader could use an existing vulnerable web application. Likewise, the reader could use test sites that allow him to practice hacker techniques in a wide variety of security realms. Just chose one from Aman Hardikar’s awesome mind map with various penetration testing practice labs and vulnerable applications (Hardikar, 2013). But on the other hand, building an infrastructure with simple IT services such as directory services, messaging services and a web stack  will allow the reader to enhance the depth and breadth of its skills not only from a security perspective but also from a systems and networking viewpoint.

Also, It is valuable to be exposed to defense and offense. Through the process of creating this environment and then growing it at will, the reader can practice both sides. In this environment a simple and secure web application is created and then its defenses are reduced. For instance, while following the mentioned book to create an ASP.NET website the code uses strong protections against SQL Injection using parameterized queries, stored procedures and data validation controls (Posey, Barnett & Darie, 2011). To make the application less secure, the reader first has to understand the security techniques employed by this application. The same applies to other technologies. For example techniques that protect against malicious user input. Once the code is vulnerable, the reader can explore attack techniques.

After building the mentioned web application – the code is available for free on GitHub -, 4 steps are executed to make it vulnerable: First, a user account with system administration privileges is created. Second,  the SQL parameterized statements are replaced by dynamic SQL statements. Third, the code is changed to make the application disclose error information and finally, the data validation code is removed to avoid input sanitization based on type, length, format or range.

For step one, go into the SQL Management Studio on your database server and create a user with system administration privilege (sysadmin) as illustrated in the left side of the following figure.
security-hot-fig5

This user will be used to define a database connection using SQL authentication. Then start changing the .NET application code using Visual Web Developer 2010 Express. For reference the right side of previous figure shows how these code files look. Next, web.config is modified. The authentication mechanism used by the application to connect to the database will change from integrated authentication to SQL authentication as shown on the left side of below figure (Posey, Barnett & Darie, 2011).  After making the change make sure the application can be compiled and is working as expected. Next change HelpDesk.aspx.cs. Remove the block of code that contains the parameterized SQL statements and replace it with a dynamic SQL as shown in right side of the following figure.

security-hot-fig6

Following that, step three is to customize the Try-Catch-Finally code block in HelpDesk.aspx.cs as shown on the below figure. This allows the web application to throw error messages and disclose them locally. Finally change HelpDesk.aspx and remove input data validation by commenting it out. This will facilitate the attack methods later on. The left side of the below figure shows the code block that should be removed or commented.

security-hot-fig7

In addition,  disable the EnableEventValidation and ValidateRequests directives by setting them to false in the header of the HelpDesk.aspx (see below figure).

security-hot-fig8

By following these steps the reader made the HelpDesk.aspx page vulnerable to SQL injection. This is going to be demonstrated in the next articles. It is not an intent to make the reader a .NET developer. Still, it is up to the reader if  he wants to further read and explore more about what are those measures that were removed or just follow the steps in order to practice the tools and tactics in the upcoming articles.

 

References:
Hardikar, A. (2013, 06). Penetration testing practice lab – vulnerable apps / systems. Retrieved from http://www.amanhardikar.com/mindmaps/Practice.html
Posey, T., Barnett, W., & Darie, C. (2011). Build your own asp.net 4 web site using c# & VB, 4th edition. SitePoint

 

Tagged , , ,

Security Hands-On-Training – Part 2

This article follows the first part of the security hands-on-training series. The focus will be on adding system components to the environment that was built on part one.

After you have setup the host environment with your virtualization software, additional components need to be installed. It is important to install and test one component at a time to minimize complexity and to keep good notes. Document each step and relevant configurations like passwords and IP addresses.

The environment needs Microsoft Windows systems. When building a Windows environment start with a Domain Controller and a Member server (TechNet, 2009). A more complex configuration is described in the Windows Server System Reference Architecture (WSSRA) documentation (Microsoft, 2005). It uses a modular approach that allows users to focus on the scenarios or services that are more relevant for their needs. With overview documents, reference blueprints, architecture blueprints, service blueprints and exhaustive implementation guides that will help the users design and implement IT services based on the use of Windows Server Systems products within the context of a real-world enterprise scenario using a fictitious organization, named Contoso (Microsoft, 2005). This documentation was written in 2005 and considers Windows Server 2003 to build foundational infrastructure services. Even though, the WSSRA is a complex set of guidance spanning more than 3,500 pages and contains more information than what is needed, it is a great guide and helps to build a Windows environment. Over time, the services covered by WSSRA are being updated and replaced with the Infrastructure Planning and Design (IPD) Series which will cover Windows Server 2008 (Microsoft, 2012). Below is the logical diagram that illustrates the infrastructure that is build throughout those guides.

hotsecurity-fig4a

In the small environment that we are building in order to perform hands-on security, two Windows machines were used. After having the first Windows machine deployed with a baseline configuration and device drivers installed from VMware Tools, the reader should sysprep it. Next, shutdown the system, compress it, and save it to a separate folder. This folder will be the repository of ready to deploy gold images. Please consider that the sysprep method is to avoid SID duplications when cloning windows machines. Mark Russinovich explains it perfectly: “The Microsoft-supported way to create a Windows installation that’s ready for deployment to a group of computers is to install Windows on a reference computer and prepare the system for cloning by running the Sysprep tool. This is called generalizing the image, because when you boot an image created using this process, Sysprep specializes the installation by generating a new machine SID, triggering plug-and-play hardware detection, resetting the product activation clock, and setting other configuration data like the new computer name” (Russinovich, 2009). In addition, after finishing the operating system and driver installation, create a snapshot to save the state of the virtual machine which will allow you to return to any point previously saved. This allows the reset of the virtual machines to a known-good previous state without the need to rebuild the systems from scratch.

The scenario that is described trough these article series uses two Windows 2008 Standard edition servers. One will have the role of Domain controller and Primary DNS server. The other will run a web server, a database server and a development framework. To get the Windows 2008 operating system media the reader can download an evaluation copy from Microsoft’s download center portal or from MSDN if it has a MSDN subscription.

The high level steps needed to create the first Windows Server 2008 are described below:

  • Install and configure Windows Server 2008.
  • Install VMware Tools.
  • Execute Sysprep.
  • Shutdown and compress to a golden image.
  • Start the new system and activate it (or use a trial).
  • Assign the VM network adapter to a custom specific network e.g. VMnet3
  • Assign a static IP address, DNS and default gateway in the desired range.
  • Ping the default gateway.
  • Run dcpromo to install Active Directory Domain Services.
  • Choose to install DNS Server and Create a new Domain in a new Forest e.g. ville.com.
  • Create a VM snapshot.

Web Stack

The next step is to build the second windows machine. This machine will be the web stack with a web server, database and a development framework. Using Windows, IIS, SQL Server and ASP.NET is one option. Another popular choice is Linux, Apache, MySQL and PHP. The first option was chosen. After some research the book “Build Your Own ASP.NET 4 Web Site Using C# & VB” was used because it gives a step-by-step approach to build a web stack using ASP.NET framework (Posey, Barnett & Darie, 2011).

The first steps are to install the required software i.e., Visual Web Developer 2010 Express Edition, .NET Framework 4 and the .NET Framework Software Development Kit (SDK), Microsoft SQL Server 2008 R2 Express Edition and SQL Server Management Studio Express  (Posey, Barnett & Darie, 2011).

Then with the web stack ready, the reader can start by creating the first Hello ASP.NET page and getting an understanding how it works in the background. While following the book and advancing trough the chapters to build the web application you will start to get familiar with topics like view state, global configuration, server and client side data validation, visual design and code-behind files, debugging and error handling and interacting with a relational database via ADO.NET (Posey, Barnett & Darie, 2011).

Below are the high level steps needed to do install the Windows Server 2008 and Web Stack:

  • Deploy Windows Server 2008 from previous golden image.
  • Start the new system, define the hostname, admin password and activate it (or use a trial).
  • Assign the VM network adapter to a custom specific network e.g. Vmnet3.
  • Assign a static IP address, DNS and default gateway in the desired range.
  • Ping the default gateway.
  • Join the system to the Domain.
  • Create a VM snapshot.

Next the high level steps to create the web stack by following the Build Your Own ASP.NET 4 Web Site Using C# & VB book  (Posey, Barnett & Darie, 2011).

  • Install IIS 7.x with ASP.NET application development support.
  • Install Visual Studio 2010 Web Express Edition.
  • Install .NET 3.5 SP1.
  • Install KB942288.
  • Install SQL Server 2008 Express R2.
  • Build the ASP.NET application.

Artillery – Tools of the Trade

After having the initial infrastructure in place the reader will need to build an arsenal of tools that will get him well equipped to practice, learn and perform offensive techniques. One of the best suites available is the Kali Linux. This distribution brings the instruments needed in order to execute the steps an intruder will eventually perform during an attack. Depending on the reader’s choice, Kali Linux is available in ISO or VMware image format.  Similarly arsenals are available like the Samurai Web Testing Framework created by Kevin Johnson of Secure Ideas and Justin Searle of UtilSec which focus on web application penetration testing (Johnson). Other alternatives exist such as Pentoo, Matrix, NodeZero, or Katana which consists of a multi-boot DVD that gathers a number of different tools and distributions in a single location (Engebretson, 2013). Moreover, the reader can choose a preferred operating system and start collecting and installing the tools needed depending on the task or technique. In our environment ,Backtrack R5, which is a precursor of Kali, will be used (Security).

Even though the BackTrack distribution is well known in the security community, many of the tools have malicious capabilities, can cause damage and take systems offline. Make sure to keep those tools in a controlled environment and behind a firewall to minimize the possibility of misuse. You never know if the tools have a hidden feature that targets the user system. In some cases, after trying the tools and techniques, the target operating system needs to be rebuilt. This is another area where VMware shines. Rather than physically reinstalling the operating system or application, its original configuration can be easily restored using snapshots.

In this case the BackTrack was installed from the ISO image and positioned into the bridge network as illustrated in part one. The default gateway on the system points to the virtual firewall’s IP address. The installation of BackTrack or Kali is easy and simple and allows the reader to have a ready system with all the tools needed.

Part 3 will describing how the ASP.NET web site code was modified in order to make the application less secure. This will allow us to understand the security techniques employed by the application in order to make it defenseless and practice our security tools and techniques!

References:

TechNet, M. (2009, 06). Step 1: Setting up the infrastructure. Retrieved from http://technet.microsoft.com/en-us/library/dd883274(v=ws.10).aspx
Microsoft. (2005, 12 04). Windows server system reference architecture (wssra). Retrieved from http://www.microsoft.com/en-gb/download/confirmation.aspx?id=15777
Microsoft. (2012, 03 1). Infrastructure planning and design guide series. Retrieved from http://technet.microsoft.com/en-gb/solutionaccelerators/ee382254.aspx
Microsoft. (2013, 11 16). Memory limits for windows releases. Retrieved from http://msdn.microsoft.com/en-us/library/windows/desktop/aa366778(v=vs.85).aspx
Russinovich, M. (2009, 11 3). [Web log message]. Retrieved from http://blogs.technet.com/b/markrussinovich/archive/2009/11/03/3291024.aspx
Posey, T., Barnett, W., & Darie, C. (2011). Build your own asp.net 4 web site using c# & VB, 4th edition. SitePoint
Security, O. (n.d.). Kali Linux. . Retrieved , from http://www.offensive-security.com/community-projects/kali-linux/
Engebretson, P. (2013). the basics of hacking and penetration testing, 2nd edition. Syngress.

Tagged , , , , , ,

Security Hands-on-Training – Part 1

The information security industry will continue to grow in size, density and specialization (Tipton, 2010). The demand for qualified security professionals who possess relevant knowledge and required skills is growing and will increase substantially (Miller, 2012) (Suby, 2013).  The information security discipline is complex and requires continuous investment in training (Suby, 2013). Recently, various articles posted in the media illustrate demand for security professionals (Ballenstedt, 2012). The Cyber workforce has also increased by 600 percent over the last few years. As an example, a search for the phrase “IT Security” on jobserve.com for IT & Telecommunications industry returned over 5000 jobs in UK. As far as the biggest Swiss job portal jobs.ch is concerned, running the same query resulted in over 300 job postings.

That being said, the following question is being raised: How can one help and facilitate the growth of these information security skills? One key method is via training and education. Even though there are plenty of systematic, formalized security training programs, the hands-on training method provides opportunities to practice skills under the most realistic conditions possible (Sisson, 2001). One option is to  build an environment that is designed to mimic real life situations by creating a simple virtual IT infrastructure lab that will allow simulating complex implementations . This creates an environment that will have the flexibility to accommodate changes by adding and removing components at will. This environment will represent real-world security issues with their respective flaws in an interactive, hands-on experience which comes with greater advantage over traditional learning methods because security issues often require substantial hands-on training in order to be understood and mastered (Erickson, 2008). In addition there is the advantage of being in a controlled environment in which unforeseen events are nonexistent or at least minimized (Gregg, 2008). By creating this environment we foster the knowledge and promote learning. Topics such as incident handling, intrusion analysis, system administration, network security, forensics or penetration testing can be practiced, explored and explained.

In order to maintain focused, we need to define a clear scope while creating such an environment. Each one of the aforementioned security domains would take several book volumes to be adequately covered. The environment is flexible enough to allow simulating any of those domains. In this article series we will focus only on familiarizing users with offensive and hacker techniques, attack methods and exploits – all of which the reader can learn, practice at his or her own pace. We won’t focus on the countermeasures or defensive techniques which can be an opportunity for the reader to conduct further research. For example, an incident handling question could be: how could you better prepare and be able to identify such attack methods? Or how could you contain, eradicate and recover from such attacks? This article series aims to provide an introduction and encourage further research using the same or similar environments.

It is important to realize that some of the techniques that will be demonstrated could be used to commit nefarious acts, and this series of articles only provides them so the reader understands how attack methods work. It is also important to understand that as a security professional, readers should only use these methods in an ethical, professional and legal manner (Skoudis & Liston, 2005) (John & Ken, 2004).

The methodology presented creates an environment that will mimic a small business network which will be modified in order to make its defenses weaker or stronger depending on the offensive tools and techniques the reader wants to practice.  In addition, a combined arms approach is used to raise awareness of how combining different tools and techniques can lead to more powerful attacks. Throughout the series of articles the reader is encouraged to practice other scenarios and further explore the techniques and move into more advanced topics.

Get the Environment Ready

Whether the reader is running Linux, Windows or OS X, a virtual environment can be easily build. There are a variety of virtualization systems and hypervisors available. The VMware Workstation was chosen due to personal preference, wide range of operating systems supported, and affordable price. Other open source and commercial solutions are available and the “thehomeserverblog.com” maintained by Don Fountain contains great articles about them.

Use at least two monitors. The system should be equipped with sufficient RAM and fast I/O like SSD drives or USB 3.0 ports. In most cases an average desktop or laptop can run 2 to 3 machines but a more powerful system with 32GB RAM and enough storage can easily perform with 18 VMs. The first system to be deployed should be a 64 bit host operating system e.g., Windows 7 Professional in order to accommodate enough RAM (Microsoft, 2013). Next the hypervisor software is installed. In this case will be VMware workstation 8. The second component that should be built is a virtual firewall that will be the gateway to the isolated and controlled environment. This is important because the reader does not want to practice tools, exploits and other nefarious software in its home or production network (John & Ken, 2004).

The firewall should have several interfaces mapping to different VMnets which will result in having different networking segments protected by firewall rules and routing. The reader can start with a single-arm DMZ. For a more realistic setup, a DMZ screened subnet approach with a dedicated segment for a management network is preferred. Moving beyond this by adding additional tiers of security is always possible at cost of proportional increase of environment complexity and resources. One of the interfaces of the firewall should be the management interface where the management traffic will reside and where the management systems are.  Another interface of the firewall is considered the external. This interface, in the VMware terminology, is configured as Bridge mode. It will connect the environment to the real-world (host network) where the reader might have his wife’s and kid’s laptop plus the wireless and router devices to be able to connect to the Internet.

The environment used here contains a distributed Checkpoint firewall but any other firewall would work. The reader should choose one that he feels comfortable with or one that he would like to learn about.  The distributed Checkpoint installation is made up of two machines: a firewall module and a management station based on SPLAT version R70. Both machines are managed using a Windows server called GUI, that contains the Smart Console client software.

hotsecurity-fig1

To optimize the install, the DHCP server will be disabled and each VMnet will be mapped to an appropriate network range.

In this environment three (3) DMZ networks were created in the firewall. Each DMZ is assigned an RFC1918 IP network range and will be mapped to a different VMware network. Below figure depicts the network diagram and the high level steps to create the environment are described on the end of this article.

hotsecurity-fig2

In terms of firewall rules the environment contains a very simple approach where HTTP traffic is allowed from anywhere to the Web server. This is a typical scenario in a small business network. Then the internal DNS server is allowed to make UDP connections towards a public DNS server. Another rule allows NTP synchronization between the various machines and a public NTP server. Management traffic that allows communicating with the firewall is defined by default as part of the implicit rules. The initial firewall rule base is shown in the figure below.

hotsecurity-fig3

Below are the high level steps that describe how to create the environment:

  1. Install the host operating system e.g. Windows 7 PRO 64bits.
  2. Install VMware Workstation 8.
  3. Configure VMnets using Virtual Network Editor.
  4. Install and configure the Checkpoint Management Station R70 in VMnet4.
  5. Install Windows OS and Checkpoint Smart Tools in VMnet4.
  6. Install Checkpoint Firewall R70.
  7. Configure the Firewall with 4 interfaces.
  8. Configure routing and define the firewall rules.
  9. Test the connectivity among the different subnets.

Part 2 will follow with windows systems and infrastructure.

 

References:

Suby, M. (2013). The 2013 (isc)2 global information security workforce study. Retrieved from https://www.isc2cares.org/uploadedFiles/wwwisc2caresorg/Content/2013-ISC2-Global-Information-Security-Workforce-Study.pdf
Skoudis, E., & Liston, T. (2005). Counter hack reloaded: A step-by-step guide to computer attacks and effective defenses, second edition. Prentice Hall..
Gregg, M. (2008). Build your own security lab: A field guide for network testing. John Wiley & Sons.
John, A., & Ken, B. (2004). Creating a secure computer virus laboratory. Manuscript submitted for publication EICAR 2004 Conference, Department of Computer Science, University of Calgary.
Erickson, J. (2008). Hacking: The art of exploitation, 2nd edition. No Starch Press.
Tipton, W. Hord, “Preface” Preface (2010). Official (isc)2 guide to the issap cbk. Auerbach Publications.
Miller, J. (2012, 10 31). Napolitano wants nsa-like hiring authority for dhs cyber workforce. Retrieved from http://www.federalnewsradio.com/473/3101703/Napolitano-wants-NSA-like-hiring-authority-for-DHS-cyber-workforce
Ballenstedt, B. (2012, 08 12). Dhs seeks cyber fellows. Retrieved from http://www.nextgov.com/cio-briefing/wired-workplace/2012/11/dhs-seeks-cyber-fellows/59197/?oref=ng-voicestop

Tagged , , , , , ,

ShellShock – Hands-On

In my previous post I gave an overview about the key events that happened during the week that GNU Bash vulnerability – Shellshock – got disclosed. In this post would like to demonstrate a hand’s on scenario that will allow one to have a better practical understanding on how someone could exploit the Shellshock vulnerability using HTTP requests to CGI scripts.

In order to better understand how this vulnerability can be exploited trough CGI scripts, below a short summary about what is CGI. CGI stands for Common Gateway Interface as formally defined in the RFC 3875. It is a gateway between the Web server and CGI scripts. You can write CGI programs in almost any programming language. The process of viewing a document on the Web starts when a Web browser sends a request to a Web server. The Web browser sends details about itself and the file it is requesting to the Web server in HTTP request headers. The Web server receives and reviews the HTTP request headers for any relevant information, such as the name of the file being requested and sends back the file with HTTP response headers. When a Web browser requests a CGI script in the cgi-bin directory from a Web server, the server knows is it is a CGI script and it executes. All the relevant data sent to the Web server from the Web browser, such as form input, plus the HTTP request headers are sent from the server to the CGI script in either environment variables or by standard input (stdin). This means the Web server makes available  all the HTTP request headers received from the Web browser to the CGI script using environment variables all of which have the HTTP_ prefix. At this states the CGI script takes over, it parses and processes all the information.  When the CGI script completes the execution, it sends the results back fo the Web server. The Web server formats the HTTP response header and returns the data to the Web browser.

shellshock-hands-1

Lets create a short example of a CGI script based on Perl that will pass back to the web browser the HTTP headers that were received trough the usage of CGI envronment variables. This was made on a CentOS machine running Apache has HTTP deamon.

shellshock-hands-code1

The same example can be done in Shell scripting using BASH.

shellshock-hands-code2

Now that we have a CGI bash script we can try out Shellshock!

The vulnerability can be easily exploited by introducing malformed HTTP headers in the request that will be processed by the CGI script as being code.  In the following scenario I have Kali Linux box and a Web Server running CentOS with Apache with mod_cgi enable.  This will be a manual attack in order to have a better practical understanding, however all this can be automated.

First we make a HTTP request to the Web Server CGI script bash.cgi using NetCat. The server answered with a HTTP 200 OK response and is respective results that were produced by the script. Next, the second HTTP request is much more interesting. As you can see we make a HTTP request to the same CGI script but now in the User-Agent field we crafted a string that will allow code execution. Because bash does not separate code from data this string will be part of environment variables. The code will be execute with the user permissions of the web server which in this case is the apache user account. In this case we just run the /usr/bin/id and as you can see the Web Server answered with the output of the id command.

shellshock-hands-2

So what can an attacker do?

This remote code execution attack vector is pretty serious because it allows to execute commands on the operating system, change configuration files and many other nasty stuff. The following picture demonstrate a scenario where an attacker via this attack vector can fully compromise a system.  The attacker opens 2 shell commands (attacker shell 1 and 2).

shellshock-hands-3

  1. Evil starts a HTTP deamon that will serve Evil stuff. It compiles a local escalation privilege exploit for Linux machines. Using Metasploit it creates a reverse shell that will connect back to the attacker on port 8080. Then it will put a NetCat listener accepting request on TCP port 8080.
  2. Then, Evil starts creating the malicious HTTP requests to the CGI script using the User-Agent field as payload for the commands. It start by downloading the local privilege escalation exploit camouflaged as JPG file to the /tmp folder which is writable by the user apache.
  3. Next it downloads the reverse shell binary.
  4. It assigns execution permissions to the reverse shell binary.
  5. It executes the reverse shell.
  6. On the NetCat listener the attacker will receive the reverse shell and will have a command line open to the system. Now he can execute the local privilge escalation exploit.
  7. Evil got root access to the system!

As you could see this was pretty easy to execute and Evil got root access into the system. Following that, Evil could retrieve the passwd and shadow file and crack the credentials accounts or he could find a way to maintain persistence and cover his tracks.

How could one increase its protection against this?

Three key recommendations : Patching , Egress traffic filtering and Hardening. By not using the latest patches and security recommendations you are exposed to this kind of scenarios. Patching is one of the most effective recommendations that someone should take. Egress filtering is extremely important nowadays, not filtering outgoing traffic to the Internet allows your internal systems to communicate with any IP address from the Internet which significantly increases the risk of downloading malicious code and be compromised. Finally, fortify your systems using the security best practices and vendor recommendations e.g. SELinux in this case would not allow Evil to initiate a socket using the apache account limiting Evil ability to download its malicious code.

The tools and tactics used are not new. However, they are relevant and used in today’s Shellshock attacks. With this kind of scenarios one can learn, practice and look behind the scenes to better know them and the impact they have.

Tagged , , , , , , ,
Rational Survivability

Hoff's Ramblings about Information Survivability, Information Centricity, Risk Management and Disruptive Innovation.

SANS Internet Storm Center, InfoCON: green

Increase security awareness. Promote, reinforce and learn security skills.

TaoSecurity

Increase security awareness. Promote, reinforce and learn security skills.

Schneier on Security

Increase security awareness. Promote, reinforce and learn security skills.

Technicalinfo.net Blog

Increase security awareness. Promote, reinforce and learn security skills.

Lenny Zeltser on Information Security

Increase security awareness. Promote, reinforce and learn security skills.

Krebs on Security

In-depth security news and investigation

Follow

Get every new post delivered to your Inbox.

Join 63 other followers