Buffer Overflow: Smashing the Stack Tutorial

Tuesday, October 22, 2013

Buffer Overflows or stack smashing are common attack vectors. There are numerous tutorials online on how to perform buffer overflows and the theories behind them, but in this example we'll dive in a little deeper.

What you'll need:



Please remember, this is solely for educational purposes. 
The techniques mentioned below are not to be used for malicious purposes outside of a controlled research environment.

Abstract


A stack overflow is accomplished when one overwrites the space allocated for the stack. Let's take a look at simple example. Below we have a program which takes a five digit zip code from a user and places it into an array of five elements. Can  you see a problem with this program?


If you were thinking that there was no bound checking you are correct! This program does not validate user input thus allowing a malicious user to input a zip code containing a thousand characters if s/he wishes. Let's check to see how the stack looks like during the execution of this program. The image below depicts the Stack Example.



For simplicity purposes I have divided the stack into three blocks. The first block will contain the zip code array, the second block will contain the saved frame pointer (ESP), and lastly the return address (EIP). Once the user inputs his/her zip code the character array will be populated as shown below.


Excellent. The program seems to be working thus far. The zip code, 89101, was stored within the zip code array just fine. However, what happens when a user decides to send a thousand characters? Let's take a look.

 

 Oops! The program has crashed. This happens because the program had no bound checking. If the program were to have implemented input validation and used the strlcpy instead of strcpy function then this could have been avoided.

Now you may be asking yourself, how exactly can someone exploit this? Well, if the user wants to inflict some damage then s/he must find enough space for their payload and make the application point to the payload at the time of the crash. Let's go through this in detail.


Example


Before we get started, be sure to go through the bullet points below to make sure you're ready to go:

  • Ensure that both of your virtual machine's (windows and kali/backtrack) network settings are set to internal/host only.
  • Install Free Float FTP and Immunity Debugger onto your Windows OS.
Great you're locked and loaded. In order to see and investigate the crash we need to attach the FTP server to a debugger, Immunity Debugger.

Open Free Float FTP and Immunity Debugger. Once inside Immunity Debugger go ahead and attach the FTP executable.

Next, click on the play button (F9) in the toolbar. We are now running the FTP server successfully under Immunity.  Check out the application's register values on the top right column within Immunity. They should look like the ones depicted below.


Now, let's move on to the fun stuff. In your Kali/Backtrack machine let's make a simple proof of concept code to see the crash happen. In this application, the buffer overflow vulnerability is trigged when a user submits 1000 characters to the application. Every application is different and requires fuzzing in order to determine the point of the crash.

Our proof of concept script below submits a thousand letter A's to the application using the FTP MKD command.

If you do not understand what this program is doing then I highly recommend you visit the python documentation.

After running the proof of concept script we can see that the FTP server registers (specifically ESP, EDI and EIP) within Immunity debugger have changed and are now populated with letter A's (EIP is populated with 41414141 which is the hex value for letter A). This means we have successfully trigged the buffer overflow vulnerability!




Now that we have overwritten EIP we must find where exactly EIP was overwritten. To do this we will use metasploit's pattern create and pattern offset scripts. The pattern create script will create a unique string for a given length. We will create a string consisting of 1000 characters and place that into our program's buffer variable.


Be sure to restart the debugger and FTP application before running the proof of concept script again. Once executed the registers will now be overwritten with the unique pattern. EIP, ESP and EDI should be overwritten. Copy the EIP value (should be 69413269) and use metasploit's pattern offset to figure out exactly where the location of EIP is at the time of the crash.



Great, we can see that the offset or location for EIP occurs at the 247th byte. Repeat this process for the other registers to obtain their respective offsets.


We now have the locations of EIP, ESP and EDI. In this example we will be placing our shellcode at the beginning of the ESP register, but first we must find an instruction to jump to our shellcode. What does this mean? Let's break that concept down.

An application is constantly performing actions and going through instructions. Our goal is to control the execution of the application. Once we control the execution then we would be allowed to insert our own instructions.


The EIP register keeps track of the address for the next instruction. In other words, it controls program execution. What we must now do is find an instruction within that says go to ESP or jmp esp which would make the application go to our shellcode.

Within Immunity click on View > Executable Modules and select user32.dll. We should now have User32.dll loaded within Immunity. Right click within the module and search for a command containing JMP ESP.



Great, we now have the JMP ESP instruction located at 768C4E5B. Now within our proof of concept we will place this value in little endian after the EIP offset followed by our shellcode after the ESP offset. I used metasploit to create shellcode to execute a windows calculator. 

Be sure to also include some NOPs (\x90) for shellcode padding and then restart the FTP application without Immunity debugger and launch the proof of concept code. There we have it! 

We have successfully exploited the buffer overflow vulnerability for Free Float FTP and hopefully obtained a better understanding of buffer overflows. Check out the full proof of concept code here.

Go Further! 


I highly encourage anyone to dive deeper into this subject matter. This example was very simple but there is much more to be learned. Go check out some of the sites mentioned below for a better understanding.

Special Thanks to b33f @ Fuzzy Security. Be sure to check out his in depth exploit development tutorial at fuzzy security.

MySQL Injection: Manual Enumeration

Friday, August 30, 2013

Let's build on last week's post and go over some manual My SQL injection techniques. After reading and trying out some combinations of manual SQLi I believe these are a good bunch to use.

If you want practice with manual SQLi I recommend loading some vulnerable web applications such as bricks, webgoat, or dvwa. You can also check out our friends at vulnhub.com for pre-built VMs.

Although tools like SQLmap make our life easier, it is still good to know how to manually test a database.


Please remember, this is solely for educational purposes. 
The techniques mentioned below are not to be used for malicious purposes outside of a controlled research environment.

Our goal in this scenario is to use a UNION SELECT query but in order use it one must first know the number of columns in the database. Let's dive into it!

Number of Columns


Detecting the number of columns can be done in two ways. The first method is using ORDER BY clauses and increment the number of columns till an error is depicted. 


The second method is using a UNION SELECT query and incrementing NULL values.



Vulnerable Columns


Great so we determined how many columns are contained in the database, but now let's see which columns are the ones depicted by the web application on our screen. To do this we provide a false query and the UNION SELECT query.



Go Enumeration


Now that we know the number of the columns being depicted on the screen we can use those to enumerate the database. In this scenario column 1,2 and 3 are being depicted so we can use any of those to query the database and see the results.

Working Directory



Database Name



Table Name



Column Name

The first number in LIMIT is the column number (i.e. LIMIT ,1) . Increase that number to see the different columns within the database.


Pulling Column Data


We now have the database name, table name, and column names. Let's pull some data from columns named 'username' and 'password'.

Hidden Bonus: Congrats! You found a hidden bonus. Use 'file_priv from mysql.user' and 'load_file('x')' to check for LFI vulnerabilities. Remember to use this in a controlled research environment and not for malicious intentions!
 That's it! There might be some modifications one might do depending on the web app (e.g. adding quotes, comments). The mitigations to this are the same as our previous post on MS SQL injection.

MS SQL Injection: Manual Enumeration

Thursday, August 22, 2013

The following post is meant to serve as a quick reference for basic database enumeration through SQL Injection (SQLi). This syntax is
for MS SQL but with some modifications it can also be applied to MySQL.

Please remember, this is solely for educational purposes. None of the techniques mentioned should be used for malicious purposes outside of a controlled research environment. 

Most of the snippets below use provide a false query followed by the OR keyword and a true statement. The true statement will contain the SQLi. Note: One may also accomplish the same by providing two truth statements.

Database Version



Database Name



Database Username

The snippet below depicts how to obtain the username that the database is being run under.


Database Table Names 

The snippet below will provide an error message showing the first table name.


One can then use the NOT IN keyword in subsequent requests to view the rest of the tables within the database.


Database Column Names 

The snippet below will provide an error message showing the first column name.


One can then use the NOT IN keyword in subsequent requests to view the rest of the columns within the database.


Column Information

The above snippets provide one with the column names for a table and while that's great what one really wants is the information inside these columns. The following snippets depict how to obtain the information within the database. Note: The userID variable is the column name.


Go Mitigation!


The snippets above show how to successfully inject sql statements into a query. This is due to the application not implementing sufficient security checks before sending it off to the database for processing. Let us explore some ways to protect against these sort of attacks.
  • Implement a check for any SQL keywords  (e.g. SELECT, UNION, NOT IN) and bad characters (e.g. !#$%&'*+-/=?^_`{|}~@[]). If the request contains any bad keywords/characters then do not proceed with the request. Note: This is to be done on the application side before the requests get to the database.
  • Use stored procedures or prepared statements. This will ensure the attacker will not modify the intention of the query. 
  • Disable features and services which are unnecessary for operations.
  • Run the database and any applications querying the database with the lowest possible privileges.
  • Stay up to date with vendor patches after they have been thoroughly tested within your environment.

Additional Reading

  • SQLi Prevention Cheat Sheet https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
  • Hidden Bonus: Congrats! You found a hidden bonus. As a pentester sometimes you won't often find machines showing error messages so one would have to perform Blind SQLi. One can use the substring method to assist with this. Here's a quick example: substring(user_name(),1,5) = 'admin'.
Special thanks to uSploit on Top Hat Sec forums for a great tutorial. Be sure to check it out his blog at http://freedomofwisdom.blog.com/

Forensics with SIFT-Workstation: How to mount and build a super timeline

Sunday, August 4, 2013

 The Sift Workstation is at its core a Ubuntu Linux distribution with pre-compiled forensic tools. Although SANS does not release new versions of the operating system frequently it is still an attractive option (especially to beginners) due to its ease of use (i.e. not having to worry about installing any software).  However, it is recommended to obtain a Linux distribution of one's choosing (I prefer Ubuntu) and install/compile the tools oneself. One would have the ability to keep tools up to date and not have to worry about incompatibilities or errors due to dependency issues. Note: If you decide to go the second route I recommend using log2timeline-SIFT over the regular log2timeline as it saves a lot of time.

This post is meant as a quick reference reminding one of how to mount and build a super-timeline using the SIFT-Workstation. There are many great tutorials posted by SANS on their forensics blog, be sure to check those out too.

Mounting an Image

Mounting an image allows forensicators to view the files within an image. The mount command is available on most if not all linux distros by default and even on apple operating systems. The following commands will mount the image under /mnt/windows_mount as read only.

Mounting a physical disk image

Use mmls on the disk image to determine the offset of the desired partition you wish to mount. In most NTFS cases this will be 32256.

Mounting a logical partition image

No offsets need to be calculated since this is a logical image.

Building the Super Timeline

The super timeline consists of combining the access, creation, or modified times for the registry, event logs and the file system. SIFT has made it easier for forensicators to create a super timeline by modifying the log2timeline command and creating the log2timeline-SIFT

It is not needed to mount a physical disk image to build a super timeline as log2timeline-SIFT will mount it for you (if not previously mounted). Note: Forensicators must first mount a logical partition image before using this command.



This will create a text file under the /cases/timeline-output-folder. The next step is to use l2t_process and build a csv file allowing one to easily sort and traverse through the entries.

Forensicators can also limit the entries by a date range as shown in the following example:

That's it! Happy Investigating!

Username Enumeration with Burp Suite Intruder

Wednesday, July 31, 2013

Burp Suite is an excellent tool used for web application security. There are a couple of tools bundled within Burp (e.g. Spider, Scanner, Intruder, Repeater and more), but in this post we will be focusing on how to use Burp Intruder to enumerate usernames on a website.

What we need:


Prerequisites:
  • Burp Suite must be installed and configured to work with the browser proxy. I use the chrome extension Proxy SwitchySharp (thanks Alton) to quickly switch between direct connection and the proxy versus having to go into the browser proxy settings every time.
Please remember, this is solely for educational purposes. This example was performed on a virtual web lab used to practice web app security.

1. Find the web page that processes usernames. Start burp with intercept on under the Proxy tab and enter a username to check for validation. The screenshot below shows username 'jamesbond' being validated (i.e. the website checks to ensure the username is not being used).


2. Since Intercept is on Burp Suite will intercept the request and display it within the Proxy tab as shown below.


3. Right Click > Send to Intruder


4. Now within Intruder there are many different attack types, however for this example the Sniper attack will work just fine. Ensure there are no extra fields other then the username parameter is being highlighted under the Positions tab. The screenshot below shows the 'Cookie' value being highlighted. Simply click on the Clear button while highlighting the value to clear the value.




5.  Click on the Payload tab within Intruder. This is where we define our payload type and options. The payload type will be left at the default value of 'simple list' whilst the payload options will be modified.

The payload options should be clear at this point. There are two methods here, one may enter one item (username in this case) at a time or populate the list by loading a text file containing usernames.




6. Almost done! Intruder also contains an option tab with a 'Grep - Match' options. We can sort the results of the enumeration attack.

If we take a look at the source code for the application, we can see that the application returns a '1' if a username is not in use. With this knowledge we can now insert some values into the Grep options within Intruder.


We add a 0 and 1 into the 'Grep-Match' options similar to the way we added usernames into the payload options above. Remember 1 is returned if the username is not taken, 0 will be returned if the username is valid and currently in use (what we want to find).


7. At the top of the Burp Suite application click on Intruder > Start attack. Sit back and watch the Brute Force attack in action.


Success! Burp Suite found two usernames from our provided list (afrid and david) as valid usernames.

Building an Executable out of a Python Program

Thursday, June 13, 2013

The purpose of this post is to learn how to create a windows executable out of a python program using the Windows operating system.

Note: This method applies to Python version 2.x. For applications written in Python 3.x use cx_Freeze instead.

What we need:

Prerequisites:
  • The Windows operating system, Python, PyInstaller and PyWin32 must be download and/or installed prior to starting this tutorial. These are easy to do, if help is needed simply google around or ask in the comments section.

1. After installing Python2.7 and PyWin32 ensure python is mapped to the PATH.



2. Extract PyInstaller, open up command prompt and CD into the directory.
3. Run 'Python Configure.py'.



4. Run 'Python Makespec.py --onefile <location_of_program>.py'




5.  Run 'Python Build.py <program_name>\<program_name>.spec'



There should now be a directory named after <program_name> (in this case 'hello_world') containing folders named 'build', and 'dist'. The executable will be within the dist directory. Enjoy!