Start Secure. Stay Secure.TM Buffer Overflows in Ten Easy Steps By SPI Labs Start Secure. Stay Secure.TM Buffer Overflows in 10 Easy Steps Table of Contents Introduction Buffer Overflows in 10 Easy Steps 1) Crash the application 2) Throw stuff at it 3) Attach a debugger 4) Is it? 5) Pattern matching 6) Breakpoint 7) Where's Waldo? 8) Adjust things 9) Shellcode 10) Exploit! Footnotes Additional Information The Business Case for Application Security About SPI Labs About S.P.I. Dynamics Incorporated Contact Information 3 3 4 5 5 6 7 7 8 9 9 10 10 11 12 14 15 15 © 2006 SPI Dynamics, Inc. All Rights Reserved. No reproduction or redistribution without written permission. ii Start Secure. Stay Secure.TM Buffer Overflows in 10 Easy Steps Introduction Buffer overflows remain a valued prize for an attacker. When found and exploited, a buffer overflow can be used to wreak wide-ranging havoc on a network or a single system, including the arbitrary execution of code in context of the application. In recent years, more developers have learned the lessons of security and begun taking measures to prevent conditions that could be leveraged to create an overflow from existing within their applications. However, these situations still exist in a multitude of applications, ready for exploitation by unscrupulous and determined attackers. This white paper will rehash much that has been written about buffer overflows, hopefully condensing all of it into an easy to read overview. The goals of this white paper are to stress the need for more thorough testing of applications to software developers, and to introduce and instruct a wider audience in finding and exploiting overflows. It should also be able to assist the casual software user in identifying critical software problems, and help to expand the ranks of non-security software professionals who can recognize and report vulnerabilities. Buffer Overflows in 10 Easy Steps The classic definition of a buffer overflow is placing something too large in a container that is too small. Buffer overflows occur when an application or process attempts to store more data in a buffer than the developer intended it to hold, which can cause information to be stored in unintended areas. An © 2006 SPI Dynamics, Inc. All Rights Reserved. No reproduction or redistribution without written permission. 3 Start Secure. Stay Secure.TM Buffer Overflows in 10 Easy Steps attacker can use the flaws that create buffer overflow conditions to overwrite sections of memory with specific commands, allowing arbitrary code execution and giving him a means to take control of vulnerable systems. This can be leveraged by an attacker to steal customer data, create a denial of service condition, or gain remote access to user or system accounts. So, how do you go about finding a buffer overflow? Here's how to test an application in ten easy steps. 1) Crash the application Where to begin? The easiest way to ferret out a buffer overflow is by doing what you normally do...running an application. If the application crashes, like most applications tend to do from time to time in their normal course of operation, try to repeat the last few things you did in an effort to recreate the crash. If you are a little less patient, or unwilling to wait for an overflow to come to you, install and configure the software in which you would like to find a vulnerability. Your best solution might be to create a VMware image of the application in question, and use that to test it for susceptibility to a buffer overflow. Make note of the application's behavior, such as the processes it starts, ports it opens, files it creates, resources it uses, and so on. Clear the system event logs, too. Services log messages when they terminate and restart, so check these logs periodically. Look over the application, and make note of the inputs that it accepts and what types of data are expected. Don't forget, files are inputs, too. The more methods of submitting data to an © 2006 SPI Dynamics, Inc. All Rights Reserved. No reproduction or redistribution without written permission. 4 Start Secure. Stay Secure.TM Buffer Overflows in 10 Easy Steps application you can find, the greater the chance that one is not secure and is susceptible to a buffer overflow. 2) Throw stuff at it Whether you use the classic "AAAAAAAAAA" buffer, or the more clever "jjjjjjjjjj" buffer[1], start small and grow the buffer. For instance, this could be as simple as appending an ever growing list of characters to the end of a URL. Other methods of input will require similar action. Sometimes it could even take special characters to break things. Remember, nothing is off limits! Don't overlook even the most innocuous input fields, and leave no field untested. When the application enforces limits or filters, find a way to bypass them. A character value can often be snuck by a filter by encoding it. For instance, %2b creates a "+" in a URL. A length limit can sometimes be defeated by simply turning off Javascript. This is the fun part of the bug hunt. If you're lucky, the process will eventually throw a Dr. Watson dialog box and then terminate. Better still, you will get the option to debug the offending program. If that happens, you can skip to step 4. Otherwise, proceed to the next step. 3) Attach a debugger Once you have restarted the application, attach a debugger. OllyDebug (www.ollydbg.de) is outstanding in this role. When Olly attaches, it pauses at a function called NTDebugBreakPoint. Take note of this address and then allow the program to continue execution (F9). Some programs use © 2006 SPI Dynamics, Inc. All Rights Reserved. No reproduction or redistribution without written permission. 5 Start Secure. Stay Secure.TM Buffer Overflows in 10 Easy Steps exceptions to handle internal housekeeping while their processes are idle. The debugger can be configured to ignore these minor irritants. Now retry the offending input. The program should attempt to crash, but the debugger will intervene by halting the soon to crash program. See Appendix A for additional debugging applications and information. 4) Is it? Identifying that your newfound bug is more than a simple DOS (basically, simply crashing a program when an error is encountered) is usually easy. First, check the instruction pointer register in your debugging application. Is it something like 0x6A6A6A6A ("jjjj"), or 0x006A006A (unicode "jj")? We have a winner! Your misbehaving has caused the program to attempt to either RETurn to, or CALL something that was overwritten by your buffer. There is a chance that the program executed a few instructions, moving the crash address a few bytes forward to something like 0x6A6A6A6F. In cases where the call or return is to an invalid address, the instruction pointer will contain the offending address. When the problem is an indirect call, the instruction pointer will be at the CALL instruction, with the intended address in another register. Maybe you were lucky, and the action caused by your buffer resulted in a jump to a valid address. The instruction pointer may not exactly reflect the address where the execution really began. On the other hand, if the problem is an invalid pointer, the instruction pointer will be at the offending instruction, but the instruction will be something boring like an © 2006 SPI Dynamics, Inc. All Rights Reserved. No reproduction or redistribution without written permission. 6 Start Secure. Stay Secure.TM Buffer Overflows in 10 Easy Steps ADD instruction. At least you have control of a pointer. Now you can possibly point the application in a new direction. 5) Pattern matching Generate a pattern, preferably a non-repeating one, the same length and format as the killer buffer from step 4. A good starting point for this pattern is "A0B0C0D0E0...A1B1C1D1E1...AaBaCaDaEa...". Drop this buffer on the application. You should see the debugger catch the same exception that was thrown when the application crashed. The address of the exception could be practically anything, but something that looks like 0x31443143 is very desirable. Convert the address bytes into their ASCII character counterparts, and find that pattern in your buffer. Remember, the address is stored opposite of reading order, so the example address would be found by searching the buffer for "C1D1". The characters at the position of the found value will first be replaced by the address of NTDebugBreakPoint for the next step. 6) Breakpoint Convert the address of NTDebugBreakPoint into characters, and overwrite the bytes of the found address with them. Don't forget, X86 has a funny byte-ordering scheme. Another thing to avoid are addresses that have bytes containing 0x00 values. Many programs use this value to signal the end of a string. Your carefully crafted buffer may be truncated by the same piece of code that you were exploiting. The work around for this nuisance is to find © 2006 SPI Dynamics, Inc. All Rights Reserved. No reproduction or redistribution without written permission. 7 Start Secure. Stay Secure.TM Buffer Overflows in 10 Easy Steps another 0xcc byte somewhere in memory. They're everywhere! Finally, place the converted address bytes over the appropriate bytes in the input string. Restart the application and attach the debugger. This time when the new buffer is dropped on the application, it should throw a breakpoint exception. This exception halts the program without modifying either registers or memory, leaving you with an unmodified system for examination. 7) Where's Waldo? If everything works as planned, you'll now be looking at NTDebugBreakPoint. If not, my condolences. Perhaps a different destination address will help. Good luck! Now you will need to find where your buffer is stored within the application. Search through the process's memory allocations with your debugging application for the data you used to overflow the buffer. There will usually be multiple instances of it, whether as a raw network buffer, or a url decoded string. Find the largest and least molested instance. Again, Olly excels by allowing wildcard searches through the programs entire memory map. Now look for that address, or any address near it on the stack. Data on the stack could be anything from a pointer to your buffer to a complete copy of the buffer. When you find it, see if any of the bytes were modified. Those are places you cannot place your payload. The size of the unmolested buffer also sets a size limit for your payload. © 2006 SPI Dynamics, Inc. All Rights Reserved. No reproduction or redistribution without written permission. 8 Start Secure. Stay Secure.TM Buffer Overflows in 10 Easy Steps 8) Adjust things Are the registers not quite pointing at the right things? You don't have to jump to your shellcode right away. Sometimes it is advantageous to first jump to other code within any one of the multitudinous DLLs linked by the application. In large blocks of binary data, many code snippets are accessible. Perhaps one of them may adjust things enough for a pointer to move to a more advantageous address for subsequent instructions. 9) Shellcode Shellcode is the payload of your overflow. It has to survive being sent to the vulnerable system, any encodings or decodings that may happen, and not contain any special characters that would interfere with execution. After all of that, it still has to do something useful to you. It could be as simple as calling MessageBoxA to deliver an annoying pop-up. A more complex challenge would be to execute an arbitrary command string. One of the most useful is to open a reverse telnet session back to your system, giving you close to total access to the now compromised system. CGISecurity.com has a wide variety to choose from. Another source of pre-built code is the metasploit project (www.metasploit.org). Pick your code, paste it and the magic offset into the appropriate place, and try it out! Though MessageBox is an annoying pop-up, this is one you will want to see because seeing it means that you have found and verified an arbitrary code execution vulnerability! © 2006 SPI Dynamics, Inc. All Rights Reserved. No reproduction or redistribution without written permission. 9 Start Secure. Stay Secure.TM Buffer Overflows in 10 Easy Steps 10) Exploit! The final exam for your exploit is the field trial. Be careful! If you choose the wrong target, this could potentially land you in federal prison. We in no way endorse any illegal activity. However, you've still found an application that is prone to buffer overflow exploitation. What can you do with it? EBay? D00D! J00 h4v3 0day! The going rate is about $4000, not bad for a few hours work. Sell it off to TippingPoint[2]. They offer cash rewards for 0-day. If you have more greed than sense, the Russian mob might also be interested. But, because you are a responsible researcher and value your well being, you will invariably choose to do the right thing and instead report the problem to the vendor's security contact. Including a simple proof-ofconcept exploit usually expedites their response. Once they have patched the problem, then feel free to tell the world, and gain yourself some much deserved recognition in the process! Footnotes [1]The ASCII character "j" is represented by the value 0x6a(106). That value is also the "PUSH imm" instruction on the X86 architecture. What makes it more clever is that this instruction is a two byte opcode. The second byte will be expanded to 4 bytes before being stored. A long string of these bytes, when executed, will simply store a bunch of 0x0000006a values on the stack. If the same string is sent through a Unicode conversion, it will still execute, but this time will store a bunch of 0x00000000 values. © 2006 SPI Dynamics, Inc. All Rights Reserved. No reproduction or redistribution without written permission. 10 Start Secure. Stay Secure.TM Buffer Overflows in 10 Easy Steps [2]http://news.com.com/Offering+a+bounty+for+security+bugs/21007350_3-5802411.html Additional Information There are several Windows debuggers available. These are two of the best. Olly Debug http://www.ollydbg.de Ida Pro http://www.datarescue.com/idabase/ If nothing else, you can utilize Visual Studio to debug an application. GDB, included with most installations, is an excellent Unix debugger. Information for GDB is available at the following link: http://www.csee.umbc.edu/courses/undergraduate/341/misc/341-gdb.html © 2006 SPI Dynamics, Inc. All Rights Reserved. No reproduction or redistribution without written permission. 11 Start Secure. Stay Secure.TM Buffer Overflows in 10 Easy Steps The Business Case for Application Security By their nature, Web applications must be accessible to be useful. Unfortunately, the same avenue that legitimate users travel to visit your Web application is also one well worn by attackers. Web application attacks have significant consequences. According to IDC/IBM Systems Sciences Institute, the inability to test and remediate vulnerabilities before an application goes into production leaves confidential data within a Web application at great risk for attack and misuse. The losses generated by this security gap are significant and expensive - up to $60 billion a year. That is only expected to increase with the passage of time. Whether a security breach is made public or confined internally, the fact that a hacker has accessed your sensitive data should be a huge concern to your company, your shareholders and, most importantly, your customers. S.P.I. Dynamics has found that the majority of companies that are vigilant and proactive in their approach to application security are better protected. In the long run, these companies enjoy a higher return on investment for their ebusiness ventures. Delivering secure Web applications can bolster an organization's bottom line by: Mitigating risks: What would be the financial cost of a successful attack upon your Web application? Of application downtime? Of fines levied because of a breach of private consumer information? From delays in shipping and billing © 2006 SPI Dynamics, Inc. All Rights Reserved. No reproduction or redistribution without written permission. 12 Start Secure. Stay Secure.TM Buffer Overflows in 10 Easy Steps because of a security incident that led to corruption of data? From a loss of competitive advantage? Increasing revenues/reducing costs: Web applications tend to rely on publicly accessible functionality as a means of generating revenue. Put simply, no ebusiness can occur if a site has been disabled by a successful attack Secure applications are far more likely to stay available, and ultimately serve to increase the confidence of users that their transactions and interactions are being conducted in a safe environment. According to Gartner, implementing security during the development process is a far more cost-effective solution than adding it after deployment. By that point, application complexity and interdependency will serve to increase update costs exponentially. Meeting policy compliance demands: Most legislative compliance packages that address online security contain these key requirements: · · Corporations must conduct a risk assessment of their applications. Web applications must contain the proper authentication, access control, and logging systems to ensure security. · Ongoing auditing of information systems must be conducted to test for newly discovered vulnerabilities. · Companies must implement an internal security policy, and show due diligence in following its provisions. © 2006 SPI Dynamics, Inc. All Rights Reserved. No reproduction or redistribution without written permission. 13 Start Secure. Stay Secure.TM Buffer Overflows in 10 Easy Steps Failure to implement the requirements of compliance legislation such as Sarbanes-Oxley or Gramm-Leach-Bliley could lead to fines, loss of revenues, bad publicity, and more. About SPI Labs SPI Labs is the dedicated application security research and testing team of S.P.I. Dynamics. Composed of some of the industry's top security experts, SPI Labs is specifically focused on researching security vulnerabilities at the Web application layer. The SPI Labs mission is to provide objective research to the security community and give organizations concerned with their security practices a method of detecting, remediating, and preventing attacks upon the Web application layer. SPI Labs continuously maintains the world's largest database of more than 5,000 application layer vulnerabilities and attack methodologies. This direct research is utilized to provide daily updates to S.P.I. Dynamics' suite of security assessment and testing software products. SPI Labs engineers comply with the standards proposed by the Internet Engineering Task Force (IETF) for responsible security vulnerability disclosure. Information regarding SPI Labs policies and procedures for disclosure are outlined on the S.P.I. Dynamics Web site at: www.spidynamics.com/spilabs/index.html. © 2006 SPI Dynamics, Inc. All Rights Reserved. No reproduction or redistribution without written permission. 14 Start Secure. Stay Secure.TM Buffer Overflows in 10 Easy Steps About S.P.I. Dynamics Incorporated Start Secure. Stay Secure. Security Assurance Throughout the Application Lifecycle S.P.I. Dynamics' suite of Web application security products help organizations build and maintain secure Web applications, preventing attacks that would otherwise go undetected by today's traditional corporate Internet security measures. The company's products enable all phases of the software development lifecycle to collaborate in order to build, test and deploy secure Web applications. In addition, the security assurance provided by these products help Fortune 500 companies and organizations in regulated industries -- including financial services, health care and government -- protect their sensitive data and comply with legal mandates and regulations regarding privacy and information security. Founded in 2000 by security specialists, S.P.I. Dynamics is privately held with headquarters in Atlanta, Georgia. For more information, visit www.spidynamics.com or call (678) 7814800. Contact Information S.P.I. Dynamics 115 Perimeter Center Place Suite 1100 Atlanta, GA 30346 Telephone: (678) 781-4800 Fax: (678) 781-4850 Email: info@spidynamics.com Web: www.spidynamics.com © 2006 SPI Dynamics, Inc. All Rights Reserved. No reproduction or redistribution without written permission. 15