Pages

Monday, January 23, 2012

Question: How does loader know ASLR is enabled for a binary?

Most people know that ASLR randomizes the base address of the binary when loaded, but how does the loader know that a binary is ASLR capable? This is a fairly easy question to answer but from what I can tell is rarely documented as a detection method and the subject of this post.

In the PEHeader->IMAGE_OPTIONAL_HEADER there is a flag called DLLCharacteristics that defines many features for the executable on load, 1 of them being ASLR. If you look here IMAGE_OPTIONAL_HEADER structure and scroll down about mid way you will see the values it defines. If you look you will also notice this defines if DEP is enabled as well.

I created a little ruby script to give you access to these values over your whole file system, directories, or a file. There are many tools like cff explorer you can use to view these per a file but this one will give you the ability to crawl a file system to find multiple files with ASLR disabled, DEP disabled and more.

git dllcharacteristics

enjoy

Thursday, January 19, 2012

QnA -> What is FS

Q: What is FS?

I wrote a challenge some time back on Securabit podcast I am a part of as a fun exercise. The question came from someone trying to reverse this challenge.
The anti-debugging technique was accessing the PEB offset +68 to detect if the debugger is attached. This is set to 70 when a debugger is attached. To find the base address of PEB I accessed FS[30] and stored that in a register.
Ok I skimmed over some items there like why is it set to 70 and what is the PEB but that is not the question. The question is what is FS.?

FS is a segment register that was added with the release of protected x86 32bit operating systems. Typically, in win32, FS points to the base of the Thread Information Block of the current active thread in PEs.

To break this down even more when you see commands such as
mov EBX, DWORD PTR DS[EAX]

the DWORD pointer is saying start with base address of DS (another segment register) and add the value EAX to this and store that in EBX. so when I accessed
mov EAX, DWORD PTR FS[30]

I was saying take the value in FS and add 30 to that and return what is there. This address stores the Base of the PEB.

Few other notes on FS:
FS[0] stores the pointer to the first SEH in the link list. This is usually called when an exception occurs in code.

FS points to the current active thread. This means a single application with multiple threads will have multiple pointers to different Thread Blocks.

Challenge
Source for Challenge

Saturday, February 5, 2011

When fuzzers miss (REVISED), Derbycon talk.

This post has been revised to reflect my talk at Derbycon on when fuzzers miss. I expanded on the explanations, added 2 more examples, code, slides and videos of each demo.

Each demo source and executable is in a zip below the corresponding video.

Link to derbycon talk







Fuzzing

Expansion fuzzing, this is the most common form of fuzzing. This is where you take a buffer and push characters inside of it slowly expanding the number of characters you push. This is to find overflows in improper bounds checking in it's simplest form.

Expansion fuzzing example:
 #!/bin/python
 from socket import *
 import sys

 if len(sys.argv) < 2:
  print "Usage: app.py ip port"

 ip = sys.argv[1]
 port = sys.argv[2]

 s = socket(AF_INET, SOCK_STREAM)
 s.connect((ip, int(port)))
 s.settimeout(2)

 for i in range(30000):
  try:
   s.send("A" * i)
   data = s.recv(1024)
   if data.chomp != "":
    print data
  except:
   pass
 s.close

Smarter:
Some fuzzers are a little more intelligent about how they handle the fuzzing process. They will take into account int wraps, special characters used in the protocol among many other things. These are fuzzers such as listed below as a small example
Spike, sully, ....

Brute force fuzzing:
Brute force is a time/accuracy trade off fuzzing. This is a technique where you try to push every variation of every character into a buffer possibly finding parsing issues or read issues. The below example is raw brute force buzzing and can take forever, it is suggested to be smart about input and not try to run this raw against a target unless you have a ton of processing power and time.

Brute force fuzzing example:
 import sys, time
 from socket import *

 class bruteforce:
  def __init__(self, ip, port):
   self.ipaddr = ip
   self.port = port

  def fuzz(self, val):
   try:
    s = socket(AF_INET, SOCK_STREAM)
    s.connect((self.ipaddr,int(self.port)))
    # Timeout for any hanging sockets
    s.settimeout(1) 
    s.send(val)
   except:
    # When fail print the characters 
    # failed to screen in hex format
    print "failed on value: "+val.encode('hex') 
   s.close
   return 0

  def run(self):
   size = 2**100000
   i = 0
   # have to use while because the size 
   # is too large to be handled in a for loop
   while i < size: 
    # convert int to hex
    val = hex(i).replace('0x', "") 
    if len(val)%2:
     # align the hex to make sure 
     # it is set to decode
     val = "0" + val 
    # decode the hex to a character
    data = val.decode('hex')
    
    self.fuzz(data)
    i += 1
    # setup timing for app so you don't 
    # flood it and fail on packets
    time.sleep(.01)     
   return 0


 if len(sys.argv) < 2:
  print "usage: brute_fuzz.py ip port"
  exit()

 # !!Warning before running this!!
 # if this prints the characters to the
 # screen it will lock up whatever prints the characters!
 # Operating systems do not like beep 
 # codes and this will flood it with beepcodes and stall

 fz = bruteforce(sys.argv[1], sys.argv[2])
 fz.run()

Listed Commands:
listing out commands that might be common exploit techniques specific for a protocol and running those quickly against a target.




This is my thought process in exploitation.
Reading:
I can not stress how important this is! Reading the application documentation, protocol RFC, and any files that get accessed by the application.
Discovery / vuln to exploit
this is a phase most of what this talk is based on so will not go over this at this point.
Technique:
this is where you get to where your shellcode is located once you have a POC running and offsets figured out.
Shellcode:
writing custom shellcode or using existing shellcode
Cleanup:
important process that can easily be skipped. review your exploit and make sure there are no bugs and see if there is anyplace you can reduce code.



This is a very simple exploit as an example to show where the vuln is located. The bottom left is the source code, the top left is the function for int overflowme() and on the right is the stack frame for overflowme(). this is what the stack looks like at point when EIP points to the call to gets.



In this slide we see the progression of the vulnerability. This shows when EIP is pointing to RETN and ready for the exploit to kick off. The conect of vulnerability vs the time the exploit kicks off is one of the keys behind this talk and is something throughout the slides I kept a theme to color all the vulnerable places in pink and the places where the exploit kicks off in red.



Time for the demos!
In each of these demos you will see bubbles the represent a function and arrows that show the order of calls and returns. if an arrow is pointing down it is a call to another function and if it is pointing up it returns back to that function. Keep an eye on the text colors as well pink = vulnerable place , red = where the exploit kicks off and what we want. Also keep in mind when something is pushed on the stack it will push up the function chain overwriting the stack frame from the higher function not the lower functions.



This is a post I made some time back that I merged into this post.



In this example we see that a char variable is set in StartProgram with a buffer size of 25. inside this function it calls get_login and prompts for a username and password. The vulnerability is in the username where it attempts to fill a 25 byte buffer with a 50 character input. This is a classic buffer overflow where EIP will be overwritten with whatever is pushed in the buffer. The trick to why a fuzzer will miss this is RETN is where the vulnerability is but it always stays in 1 function lower then where we work in unless we successfully log in.


demo1.zip



By finishing out the application and tearing down each stack frame we where now able to trigger our exploit.

Watch the stack when inputting data into a buffer, you should always follow the data you input in a buffer.




Threads can be really troublesome in exploit development. The only thread that really matters is the main thread that the application is running in. Any other thread can be destroyed at any period in time and no effect the application. This key problem will leave us with a vulnerability hanging out there without triggering the place the exploit kicks off.

We will also look at stacks and variables to show that when you overflow a buffer you are not just overwriting RETN address but also the data from other local vars below it and how this can cause issues.



In this example we have a single thread that opens off of startApp then calls authenticate to get the username and password. I have "main thread" shown next to the branching thread just to represent the fact that there are 2 threads running at that point. The vulnerability is in the password field allows 200 byte character set to be pushed into a 20 byte buffer and the exploit kicks off when this function returns. The key here is looking at verifyAuth and seeing when auth fails it just kills that thread and opens a new one with startApp(). To get this exploit to kick off we need to be able to successfully log in to break down the function block for veryfyAuth -> authenticate.

In the video I will also show examples where authenticate fails to auth because we stomp on the username on the stack causing the auth process to fail. This is another key that will cause you sometimes to hit the incorrect path to let an exploit trigger by just pushing As into the buffer without knowing what that buffer holds.

Demo2 Part1


Demo2 Part2




This can be tricky to find but taking the normal logic of following the data should allow you to see the overflow happen. From this point it is just looking at where the thread is terminated and trying to find a way to get it to start returning higher up the stack frames.

Also as shown in the video the location that the buffers get filled cause the overflow to stomp on a local variable before it. Paying attention to what buffer is for what can sometimes be challenging when following process. Setting a memory or hardware breakpoint on access to stack frames can sometimes help find this but most time this is just going to be manual work of watching where the buffers are located. One key thing to note here is the fact that if this where a pointer pushed onto the stack and not a variable you not may have control over execution in the future, so watch those local variables and overwrite to see if they may be used in a future path.



In this example we will start a look into the heap and something fairly obvious but often used exit(). The heap can often be a great place to show many examples of where fuzzers just fail at finding the exploitable areas. Most of the protections on the heap do not target the allocation but the free calls to the chunks. Just like RETN this has to do with watching for the place where the exploit kicks off and not watching the vulnerable call. Heap can have a lot of examples and location where the exploit kicks off so this makes things more difficult, in a use after free example we have to look for the use then an allocation in the future, in a double free we need to make sure we are looking for that second free and taking the correct path to make sure we are getting to it just to name a few.



In this example we will look at crashing an application using a standard heap overflow and a free to cause a crash when validating the free list. This application is a simple echo program, all it does is echo out anything you send it. After the first echo it will ask if you would like to keep echoing output, if Y then it will allocate the initial echo to heap using heapalloc and then continue to echo out in a while 1 loop anything you put in. the trick here to access free is to get out of the echo loop free the heapalloc and exit the application. To access free you need to type quit() which is not told to you. I put the hidden quit in because reversing and finding pathing such as this sometimes can help you get back where you need to be.

[video] !!!Video is on my desktop and have not put time into edit it, it will be here someday!!!
demo3.zip



heap is more difficult in every way then stack overflows including finding flaws so some practice and thinking on where the exploit kicks off with practice will help find heap exploits



These are only a few examples of limitless possible reasons why buffers may have an overflow and not trigger the exception. The main thing to take form this is the thought process.



Here are some things I use to find exploits such as this.
- when pushing data into an application pay attention to functions and understanding how this would look like in C. If you want to find the exploitable area and not just the vuln follow the data.
-break/log RETN, Watch the call stack/ pathing/ stack frame. Also if program is threaded make sure to check all stack frames and not just the current thread's stackframe.
-break/log Free/alloc, When watching for heap exploit break on what controls the heap structure and dump the heap chunks
-all references to, find anything that references the data you pushed in to see if it is used someplace later in a strcat, strcpy or anything of this type
-diffing, if the program is already patched don't take the time finding the exploit when they give it to you in a diff
-all intermodule calls, use all call function calls to find where you may want to look and pull out specific stack frames looking for user controlled data
-tracing, this can take a ton of time but tracing application paths and finding areas you are not hitting looking for data to be accessed can help.
-Work!, this is not all easy so it is going to take some thinking and some of your own ideas.



if you have any questions or comments please post below, hit me up on twitter or irc

Monday, August 23, 2010

FOAM file fuzzer

FOAM is a general purpose file fuzzer I wrote in order to find offset values quickly. It is written in python so you will need http://www.python.org/ on your system.



The script can be downloaded at https://sites.google.com/site/myneuslayout/tools

Tuesday, August 3, 2010

From 0x90 to 0x4c454554, a journey into exploitation.

I put some time in and compiled a list in a course type layout to help people in process of learning exploit development. I hope my research will help others spend more time learning and less time searching.

First off I want to thank the corelan guys for the help they have provided me so far in the process.

layout: I will be posting in a hierarchical structure, each hierarchy structure should be fully understood before moving on to the next section. I will also post sets of Parallel learning topics that you can use to study in line with other topics to help prevent monotony. These Parallel areas will have a start and end mark which shows when they should be complete in perspective to the overall learning

desktop background Link to Backgrounds

Other Posts like this one:
Because of quality of these posts I wanted to put them at the top. I could not figure out where to put them in the list because they cover so much.
past-present-future of windows exploitation
smashing the stack in 2010
IT-Sec-catalog


  1. Part 1: Programming

  2. Parallel learning #1:(complete this section before getting to the book "Hacking Art of exploitation")
    While going through the programming area I concentrate on core topics to help us later on with exploit writing. One area that is very good to pick up is some kind of scripting language. Listed below are some of the most popular scripting languages and ones I feel will prove to be the most useful.

    Python: One of my favorite languages and growing in popularity python is a powerful language that is easy to use and well documented.
    Learn Python the hard way
    Wikibooks Python
    http://docs.python.org/
    onlinecomputerbooks.com
    Grey hat python

    Ruby: If you plan on later on working inside of metasploit this may be the language you want to start with. I highly suggest this for exploit developers to learn.
    Wikibooks Ruby
    LittleBookOfRuby
    Ruby Programmers Guide
    onlinecomputerbooks.com

    Perl: An older language that still has a lot of use perl is one of the highest used scripting languages and you will see it used in many exploits. (I would suggest python over perl)
    [book] O'Reilly Learning Perl
    onlinecomputerbooks.com


    C and C++ programming:
    It is very important to understand what you are exploiting so to get started let us figure out what we are exploiting. You do not need to go through all of these but when finished with this section you should have a good understanding of C and C++ programming.
    Cprogramming.com
    http://www.java2s.com/Tutorial/C/CatalogC.htm
    http://beej.us/guide/bgc/
    onlinecomputerbooks.com

    X86 Assembly:
    Ok now to understand what the computer reads when we compile C and C++. I am going to mostly stick to the IA-32(X86) assembly language. Read the first link to understand why. It explains it very well.
    Skullsecurity: Assembly
    Windows Assembly Programming Tutorial
    http://en.wikibooks.org/wiki/X86_Assembly
    [book]The Art of Assembly
    Assembly primer for hackers
    PC Assembly Language

    Windows Programming:
    This is to help understand what we are programming in and the structure of libraries in the OS. This area is very important far down the line
    http://en.wikibooks.org/wiki/Windows_Programming
    https://upload.wikimedia.org/wikipedia/commons/5/57/Windows_Programming.pdf
    http://www.relisoft.com/win32/index.htm 
    http://slav0nic.org.ua/static/books/C_Cpp/theForger's_Win32APITutorial.pdf
    http://www.winprog.org/tutorial/start.html
    [book]Windows Internals 5
    [book]Windows Internals 4

    Disassembly:
    Dissassembly is not as much programming as it is what the computer understands and the way it is interpreted from CPU and memory. This is where we start getting into the good stuff.
    http://en.wikibooks.org/wiki/X86_disassembly
    The Art of Disassembly



  3. Part 2: Getting started

  4. Now that we have a very good understanding of programming languages and what the machine is doing we can start working on task at hand, exploitation.
    Here I will start a lot of the learning in very much a list format and adding in comments or Parallel learning areas when needed.

    Smash the stack for fun and profit (Phrack 49)
    C function call conventions and the stack
    Anatomy of a program in memory
    Function Calls, Part 1 (the Basics)
    IA-32 Architecture
    [videos]Code Audit from cryptocity.net

    (Parallel learning #1 finished: You should now have finished on Parallel learning 1 and have a good understanding of one of the 3 languages)

    [Book]Hacking art of exploitation [Chapter 1&2]
    Corelan T1
    Corelan T2

    Parallel learning #2:(complete this section before end of part 2)
    (Read the first few posts on this blog has some good info)
    Kspice blog
    (Read some of the post from this blog they are very helpful with starting out with fuzzers.)
    Nullthreat's blog
    (I am linked directly to a demo exploit for this area but this is a useful blog to keep track of for many things)
    A demo exploit

    tenouk.com: Buffer overflow intro
    The Tao of Windows Buffer Overflow
    nsfsecurity on BOF
    Hacker center: BOF
    [video]Buffer overflow Primer
    [Book]Shellcoder's Handbook Ch1&2
    [Book]Hacking art of exploitation [Chapter 3]
    Corelan T3A
    Corelan T3B
    SEH Based Exploits and the development process
    SEH overwrite simplified

    ((Parallel learning #2 finished:)


  5. Part 3:Tools of the trade

  6. This is a list of tools I have started using and find very useful.
    Immunity Debugger
    Ollydbg
    Windbg
    IDA Pro
    explorer suite
    Sysinternals

    And here are some corelan posts on how to use them. I will supply more in future but this is a very good start.
    Corelan T5
    Corelan: Immunity debugger cheatsheet


  7. Part 4: Network and Metasploit

  8. (Networking)
    Beej.us network programming
    [Book]Hacking art of exploitation [Chapter 4]
    Socket Programming in ruby

    (Metasploit)
    [Video]Security Tube: Metasploit Megaprimer
    Metasploit.com
    Metasploit Unleashed
    [video]Metasploit Louisville Class
    Metasploitable (a target)
    Corelan T4
    intern0t: developing my first exploit
    [video]DHAtEnclaveForensics: Exploit Creation in Metasploit
    Wikibooks Metasploit/Writing Windows Exploit


  9. Part 5: Shellcode

  10. Corelan T9
    projectShellcode: Shellcode Tutorial
    [Book]Shellcoder's Handbook Ch3
    [Book]Hacking art of exploitation [Chapter 5]
    Writing small shellcode
    Shell-storm Shellcode database
    Advanced shellcode


  11. Part 6: Engineering in Reverse

  12. Parallel Learning #3:(constant place to reference and use for reversing)
    Understanding Code
    Reverse Engineering the World
    Reversing for Newbies
    Room362.com reversing blog post
    Ethicalhacker.net intro to reverse engineering
    acm.uiuc.edu Intro to Reverse Engineering software
    [Book]Reversing: secrets of reverse engineering
    [video]Reverse Engineering from cryptocity.net
    CrackZ's Reverse Engineering Page
    Reverse engineering techniques
    CBM_1_2_2006_Goppit_PE_Format_Reverse_Engineer_View
    HistoryofPackingTechnology
    Windows PE Header
    OpenRCE Articles

    [GAME]Crackmes.de


  13. Part 7: Getting a little deeper into BOF

  14. Parallel Learning #4:(To the end of the course and beyond)
    Find old exploits on Exploit-db download them, test them, rewrite them, understand them.

    (Part A: preventions)
    Buffer overflow protection
    The evolution of Microsoft's Mitigations
    Purdue.edu: Canary Bit
    Preventing the exploitation of SEH Overwrites with SEHOP
    Bypassing SEHOP
    Wikipedia Executable space protextion
    Wikipedia DEP
    Bypassing Hardware based DEP
    Wikipedia ASLR
    Symantec ASLR in Vista
    Defeating the Stack Based Buffer Overflow Prevention
    Corelan T6
    Return to libc
    [video] microsoft protections video

    (Part B: Advanced BOF)
    [video]Exploitation from cryptocity.net
    Corelan T7
    Corelan T8
    Corelan T10
    Virtual Worlds - Real Exploits

    [GAME]Gera's Insecure Programming
    [GAME]Smash the stack wargaming network


  15. Part 8: Heap overflow

  16. Heap Overflows for Humans-101
    rm -rf / on heap overflow
    w00w00 on heap overflow
    [book]Shellcoder's Handbook Ch4&5
    h-online A heap of Risk
    [video]Defcon 15 remedial Heap Overflows
    heap overflow: ancient art of unlink seduction
    Memory corruptions part II -- heap

    [book]Read the rest of Shellcoder's Handbook


  17. Part 9: Exploit listing sites

  18. Exploit-DB
    Injector
    CVE Details
    Packetstorm
    CERT
    Mitre
    National Vulnerability Database

    (bonus: site that lists types of vulnerabilties and info)
    Common Weakness Enumberation


  19. Part 10: To come

  20. 1. Fuzzing
    2. File Format
    3. and more

    If anyone has any good links to add post a comment and I will try to add them or send me the link and I will review and add it.

    If anyone finds any bad or false information in any of these tutorials please let me know. I do not want people reading this getting bad information.

Thursday, May 13, 2010

practice makes perfect

This is a list of sites and images where you can practice your skills. Enjoy!

http://de-ice.net/hackerpedia/index.php/De-ICE.net_PenTest_Disks

http://www.kioptrix.com/blog/?page_id=135
http://netwars.info/
http://www.dvwa.co.uk/
http://www.damnvulnerablelinux.org/
http://hackerdemia.com/
http://www.badstore.net/
http://www.mavensecurity.com/web_security_dojo/
http://www.fatetek.net/training.shtml
http://www.net-force.nl/challenges/
http://www.enigmagroup.org
http://listbrain.awardspace.biz
http://haxme.org/missions/
http://www.hackquest.de/index.php
http://www.hackthissite.org/
http://challenges.ihtb.org/
http://www.dareyourmind.net/menu.php
http://www.intruded.net/wargames.html
http://www.hellboundhackers.org/
http://www.bright-shadows.net/
http://www.irongeek.com/i.php?page=security/deliberately-insecure-web-applications-for-learning-web-app-security
http://www.makeuseof.com/tag/top-5-websites-to-learn-how-to-hack-like-a-pro/
http://www.try2hack.nl/
http://www.astalavista.com/index.php?app=hackingchallenge
http://www.trythis0ne.com/?page=home
http://www.hackertest.net/
http://hax.tor.hu/warmup1/
http://www.caesum.com/game/
http://crackmes.de/
http://www.hack4u.org/index.php?choices=1&code=level0
http://community.core-sdi.com/~gera/InsecureProgramming/
http://testasp.acunetix.com/Templatize.asp?item=html/about.html
http://test.acunetix.com/disclaimer.php
http://ha.ckers.org/challenge/
http://ha.ckers.org/challenge2/
http://community.core-sdi.com/~gera/InsecureProgramming/LinkedBy.html
http://www.overthewire.org/wargames/
http://www.smashthestack.org/
http://www.wechall.net/index.php
http://hackme.ntobjectives.com/
http://wocares.com/xsstester.php
http://www.osix.net/
http://projecteuler.net/index.php?section=problems
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3
http://www.rootcontest.com/
http://www.cyber-wars.com/
http://roothack.org/
http://www.mod-x.co.uk/main.php
http://www.introversion.co.uk/uplink/about.html
http://whitewolfsecurity.typepad.com/
https://www.vte.cert.org/vteweb/RequestAccess/GetAccess.aspx
http://lost-chall.org/
http://hax.tor.hu/peek/
http://www.hacker.org/
http://thisislegal.com/
http://www.happyhacker.org/wargame/index.shtml
http://neworder.box.sk/link.php
http://www.webantix.net/hacking/war-games-current-and-past-hacking-simulators-and-challanges/
http://www.lifedork.net/wargames-online-hackers-training.html
http://www.room362.com/blog/2009/5/29/getting-your-fill-of-security.html
http://hack.thebackupbox.net/cgi-bin/pageview.cgi?page=wargames
http://ace.delos.com/usacogate
http://zero.webappsecurity.com/banklogin.asp?serviceName=FreebankCaastAccess&templateName=prod_sel.forte&source=Freebank&AD_REFERRING_URL=http://www.Freebank.com


(if anyone had anything to add to these let me know and I will update the list.)