CEHv6 Module 24 Buffer Overflows pdf pdf

  

Ethical H ackin g an d

Coun term easures Coun term easures Version 6

  Mo d u le XXIV Mo d u le XXIV Buffer Overflows News Source: http:/ / w w w .new s.com /

Scen ario

  It was a job that Tim wan ted right from the start of his career. Bein g a Project Man ager at a well-kn own software firm was defin itely a sign of prestige. But n ow, his credibility was at stake.

  The last project that Tim han dled failed to deliver because the application crashed. The custom er of Tim 's com pan y suffered a huge fin an cial loss. g At the back of his m in d, som ethin g was n aggin g Tim ...

  H ad he asked his Test En gin eers to do a thorough testin g of the delivered package, this would n ot have happen ed. h d l d k h ld h h d

  Module Objective

This m odule will fam iliarize you with :

  • Buffer Overflows • Reason s for buffer overflow attacks R f b ff fl tt k
  • Un derstan din g Stacks an d H eaps
  • Types of buffer overflow
  • Detectin g buffer overflows in a program g p g
  • Attackin g a real program
  • Defen se Again st Buffer Overflows • Buffer overflow detection tools
  • Libsafe • Libsafe • Sim ple buffer overflow in C

Module Flow

  Buffer Overflows Attackin g a real program

  Reason s for Buffer Overflow Attacks

  Defen se Again st Buffer Overflows

  Un derstan din g Buffer Overflow Attacks

  Buffer overflow Buffer Overflows g

  Stacks an d H eaps Libsafe detection tools

  Si l b ff fl i C Detectin g buffer

  Libsafe Types of buffer overflow

  Sim ple buffer overflow in C Detectin g buffer overflows in a program Real World Scen ario Source: http:/ / w w w .heise-online.co.uk/

Why are Program s/ Application s Vuln erable Vuln erable

  Boun dary checks are n ot don e fully or, in m ost cases, they are skipped en tirely Boun dary checks are n ot don e fully or in m ost cases they are skipped en tirely Program m in g lan guages, such as C, have errors in it Program m in g lan guages such as C have errors in it The strcat() , strcpy() , sprin tf() , vsprin tf() , bcopy() , gets() , an d scan f() calls in C lan guage can be exploited because these fun ction s do n ot check to see if the lan guage can be exploited because these fun ction s do n ot check to see if the buffer, allocated on the stack, is large en ough for the data copied in to the buffer P Program s/ application s are n ot adhered to good program m in g practices / li ti t dh d t d i ti

  Buffer Overflows

  A gen eric buffer overflow occurs when a buffer that has been allocated a specific storage space, has m ore data copied to it than it can handle ifi h d i d i h i h dl Con sider the followin g source code. Wh en the source is com piled an d turn ed in to a program an d the program is run , it will assign a block of m em ory 32 in to a program an d the program is run it will assign a block of m em ory 32 bytes lon g to hold the n am e strin g

  #include<stdio.h> int main ( int argc int main ( int argc , char char **argv) argv) { char target[5]=”TTTT”; char attacker[11]=”AAAAAAAAAA”; strcpy( attacker,” DDDDDDDDDDDDDD”); printf(“% \n”,target); return 0; }

  This type of vuln erability is prevalen t in UNIX- an d NT-based system s

  Reason s for Buffer Overflow Attacks Attacks

  Buffer overflow attacks depen d on two thin gs:

  • The lack of boun dary testin g
  • A m achin e that can execute a code that resides in the data/ stack segm en t

  The lack of boun dary is com m on an d, usually, the program en ds with the segm en tation fault or bus error In order to exploit buffer overflow to gain access to or escalate privileges, the In order to exploit buffer overflow to gain access to or escalate privileges the offen der m ust create the data to be fed to the application Ran dom data will gen erate a segm en tation fault or bus error, n ever a rem ote g g

  , shell or the execution of a com m an d

Kn owledge Required to Program Buffer Overflow Exploits Buffer Overflow Exploits

  C fun ction s and the stack C f ti d th t k A littl k A little kn owledge of assem bly/ m achin e lan guage l d f bl / hi l

  H ow system calls are m ade (at the m achin e code level) H o s stem calls a e m ade (at the m achin e code le el) exec( ) system calls e ec( ) s stem calls H ow to guess som e key param eters H o to guess som e ke param eters

  Un derstan din g Stacks

  The stack is a (LIFO) m echan ism that com puters use to pass argum en ts to fun ction s as well as to refer to the local variables refer to the local variables

  SP SP points here BP anywhere

  It acts like a buffer, holdin g all of the It acts like a buffer, holdin g all of the

  within the within the

  in form ation that the fun ction n eeds

  stack frame

  The stack is created at the begin n in g of a fun ction an d released at the en d

  Stack

  of it

  growth direction direction

Un derstan din g H eaps

  The heap is an area of m em ory utilized by an application an d is allocated dyn am ically at the run tim e is allocated dyn am ically at the run tim e Static variables are stored on the stack alon g with the data allocated usin g the m alloc in terface the data allocated usin g the m alloc in terface

Types of Buffer Overflows: Stack- Based Buffer Overflow Based Buffer Overflow

  A stack overflow occurs when a buffer has been overrun in the stack space Malicious code can be pushed on the stack The overflow can overwrite the return poin ter so that the flow of con trol switches to the m alicious code C lan guage an d its derivatives offer m an y ways to put m ore data than an ticipated in to a buffer Con sider an exam ple program given on the n ext slide for sim ple un con trolled overflow

  • The program calls the p g bof() fun ction
  • • On ce in the bof() fun ction , a strin g of 20 As is copied in to a buffer that holds 8 bytes, resultin g in a

    buffer overflow

A Sim ple Un con trolled Overflow of the Stack the Stack

  /* This is a program to show a simple uncontrolled overflow of the stack. It will overflow EIP with 0x41414141, which is AAAA in ASCII. */ #include <stdlib.h> #include <stdio.h> #include <string.h> int bof() { char buffer[8]; /* an 8 byte character buffer */ strcpy(buffer,"AAAAAAAAAAAAAAAAAAAA"); /*copy 20 bytes of A into the buffer*/ return 1; /*return return 1; /*return, this will cause an access violation due to stack corruption.*/ this will cause an access violation due to stack corruption */ } int main(int argc, char **argv) { bof(); /*call our function*/

/*print a short message, execution will never reach this point because of the

overflow*/ printf(“Lets Go\n"); return 1; /*leaves the main function*/ }

Stack Based Buffer Overflows

  Bottom of Stack Data on Stack S Bottom of Stack

  Data on Stack S Bottom of Stack Data on Stack

  S Som e data m ay be Segm en t

  SP Segm en t Return Address

  Segm en t New Return Address m ay be overwritten

  4 Bytes More Data on Stack Segm en t n Bytes

  Overwritten Data on Stack Segm en t Machin e Code. Ex.

  Execve(/ bin / sh) n Bytes + n ew data En d of Stack k h k ll

  SP SP S ta ck, w h e n Atta cke r ca lls k h f i A N o rm a l S ta ck a fu n ctio n S ta ck, w h e n fu n ctio n s m a s h e s a s ta ck

Types of Buffer Overflows: H eap- Based Buffer Overflow Based Buffer Overflow

  Variables that are dyn am ically allocated with fun ction s, such as Variables that are dyn am ically allocated with fun ction s such as m alloc(), are created on the heap In a heap-based buffer overflow attack, an attacker overflows a buffer that is placed on the lower part of heap, overwritin g other dyn am ic variables, which can have un expected an d un wan ted effects If an application copies data without first checkin g whether it fits in to the target destin ation , the attacker could supply the application with a piece of data that is large, overwritin g heap m an agem en t in form ation In m ost en viron m en ts, this m ay allow the attacker to con trol over the program s execution program ’s execution

  H eap Mem ory Buffer Overflow Bug /*heap1.c – the simplest of heap overflows*/ #include <stdio.h> #include <stdlib.h> #i l d dlib h int main(int argc, char *argv[]) { { char *input = malloc (20); char *output = malloc (20); strcpy (output, "normal output"); strcpy (input, argv[1]); printf ("input at %p: %s\n", input, input); printf ("output at %p: %s\n", output, output); printf( \n\n%s\n , output); printf("\n\n%s\n", output); }

  H eap-Based Buffer Overflow in put=m alloc(20 ); output=m alloc(20 );

  “n orm al output\ 0 ”

  XXXXXXXXXXXXXXXXXXXX output m alloc(20 ); n orm al output\ 0

  XXXXXXXXXXXXXXXXXXXX

H e a p : B e fo re Ove rflo w

in put=m alloc(20 ); output=m alloc(20 ); rdfn ordfn ord\ 0 fnordfnordfnordfnordfnord fn 0

  

H e a p : Afte r Ove rflo w Un derstan din g Assem bly Lan guage The two m ost im portan t operation s in a stack: The two m ost im portan t operation s in a stack:

  • 1. Push – put on e item on the top of the stack
  • 2. Pop – "rem ove" on e item from the top of the stack

  T Typically, return s the con ten ts poin ted to by a poin ter an d chan ges i ll h i d b i d h the poin ter (n ot the m em ory con ten ts)

  Shellcode

  Shellcode is a m ethod to exploit stack-based overflows Shellcode is a m ethod to exploit stack based overflows Shellcodes exploit com puter bugs in how the stack is han dled p p g Buffers are soft targets for attackers as they overflow easily if the con dition s m atch con dition s m atch

  "\x2d\x0b\xd8\x9a\xac\x15\xa1\x6e\x2f\x0b\xdc\xda\x90\x0b\x80\x0e" "\x92\x03\xa0\x08\x94\x1a\x80\x0a\x9c\x03\xa0\x10\xec\x3b\xbf\xf0" "\xdc\x23\xbf\xf8\xc0\x23\xbf\xfc\x82\x10\x20\x3b\xaa\x10\x3f\xff" "\x91\xd5\x60\x01\x90\x1b\xc0\x0f\x82\x10\x20\x01\x91\xd5\x60\x01" On e way is to look at the source code

  An other way is to feed the application with huge am oun ts of data an d check for the abn orm al behavior

  H ow to Detect Buffer Overflows in a Program in a Program There are two ways to detect buffer overflows: There are two ways to detect buffer overflows:

  • In this case, the hacker can look for strin gs declared as local variables in fun ction s or m ethods an d verify the presen ce of boun dary checks
  • It is also n ecessary to check for im proper use of stan dard fun ction s, especially those related to strin gs an d in put/ output

  

Attackin g a Real Program

  Assum in g that a strin g fun ction is bein g exploited, the attacker can g g g p , sen d a lon g strin g as the in put This strin g overflows the buffer an d causes a segm en tation error This strin g overflows the buffer an d causes a segm en tation error The return poin ter of the fun ction is overwritten, an d the attacker po o o o , d succeeds in alterin g the flow of execution

If the user has to in sert his code in the input, he/ she has to: If th h t i t hi d i th i t h / h h t

  • Kn ow the exact address on the stack
  • Kn ow the size of the stack
  • Make the return poin ter poin t to his code for execution

NOPS

  Most CPUs have a No Operation (NOP) in struction – it does n othin g but advan ce the in struction poin ter in struction poin ter Usually, you can put som e of these ahead of your program (in the strin g) As lon g as the n ew return address poin ts to a NOP, it is OK Attacker pads the begin n in g of the in ten ded buffer overflow with a lon g run of NOP in struction s (a NOP slide or sled) so the CPU will do n othin g un til it gets to the 'm ain even t' (which preceded the 'return poin ter') Most in trusion detection system s (IDSs) look for sign atures of NOP sleds ADMutate (by K2) accepts a buffer overflow exploit as in put an d ran dom ly creates a ADMutate (by K2) accepts a buffer overflow exploit as in put an d ran dom ly creates a fun ction ally equivalen t version (polym orphism )

  H ow to Mutate a Buffer Overflow Exploit Exploit For the NOP portion For the NOP portion

  • Ran dom ly replace the NOPs with fun ction ally equivalen t segm en ts of code (e.g.: x++; x-; ? NOP NOP)

  For the "m ain even t"

  • Apply XOR to com bin e code with a random key un intelligible to A l XOR t bi d ith d k i t lli ibl t

  IDS. The CPU code m ust also decode the gibberish in tim e in order to run the decoder. By itself, the decoder is polym orphic an d, therefore, hard to spot

  For the "return poin ter"

  • Random ly tweak LSB of pointer to land in the NOP-zon e R d l t k LSB f i t t l d i th NOP

  On ce the Stack is Sm ashed...

  On ce the vuln erable process is com m an deered, the attacker has p , the sam e privileges as the process an d can gain n orm al access.

  H e/ she can then exploit a local buffer overflow vuln erability to gain super-user access Create a backdoor

  • Usin g (UNIX-specific) in etd
  • Usin g Trivial FTP (TFTP) in cluded with Win dows 20 0 0 an d som e

  UNIX flavors

  Use Netcat to m ake raw an d in teractive con n ection s

  • Shoot back an Xterm in al con n ection
  • UNIX-specific GUI

Defen se Again st Buffer Overflows Overflows

  M Man ual l Di Disablin g bli Safer C S f C Com piler auditin g of stack library techn iques code execution support

Tool to Defen d Buffer Overflow: Return Address Defen der (RAD) Return Address Defen der (RAD)

  RAD i i RAD is a sim ple patch for the com piler that autom atically creates a safe area l t h f th il th t t ti ll t f to store a copy of return addresses After that, RAD autom atically adds protection code in to application s an d com piles them to defen d program s again st buffer overflow attacks RAD does n ot chan ge the stack layout

Tool to Defen d Buffer Overflow: StackGuard StackGuard

  StackGuard: Protects system s from stack sm ashin g attacks StackGuard is a com piler approach for defen din g program s an d system s again st "stack sm ashin g" attacks Program s that have been com piled with StackGuard are largely im m un e to stack sm ashin g attacks Protection requires n o source code chan ges at all. When a vuln erability is exploited, StackGuard detects the attack in progress, raises an in trusion alert, an d halts the victim ’s program

Tool to Defen d Buffer Overflow: Im m un ix System Im m un ix System

  Im m un ix System is an Im m un ix-en abled RedH at Lin ux distribution an d suite of th li the application -level security tools ti l l it t l Im m un ix secures a Lin ux OS an d application s Im m un ix works by harden in g the existin g software com pon en ts an d platform s so that attem pts to exploit security vuln erabilities will fail safe The com prom ised process halts in stead of givin g con trol to the attacker, an d then is restarted

  Vuln erability Search: NIST 1

  Vuln erability Search: NIST 2

  Valgrin d

  Valgrin d is a suite of sim ulation -based debugging and profiling tools for g gg g p g program s run n in g on Lin ux

  The system con sists of a core which pr ovides a syn thetic CPU in software an d a The system con sists of a core, which provides a syn thetic CPU in software, and a series of tools, each of which perform s som e kin d of debuggin g, profilin g, or sim ilar task

Various tools presen t in Valgrin d are:

  • Mem check detects m em ory-m an agem en t problem s in program s
  • Cachegrin d is a cache profiler
  • Cachegrin d is a cache profiler
  • H elgrin d fin ds data races in m ultithreaded program s
  • Callgrin d is a program profiler
  • Massif is a heap profiler
  • Lackey is a sim ple profiler and m em ory tracer

  L k i i l fil d t

  Valgrin d: Screen shot

  In sure++ In sure++ is a run tim e m em ory an alysis an d error detection tool for C an d C++ that autom atically iden tifies a variety of difficult-to-track an d C++ that autom atically iden tifies a variety of difficult to track program m in g an d m em ory-access errors, alon g with poten tial defects an d in efficien cies in m em ory usage

Errors that In sure++ detects in clude:

  • Corrupted heap an d stack m em ory
  • Use of un in itialized variables an d objects
  • Array an d strin g boun ds errors on heap an d stack
  • Use of dan glin g, NULL, an d un in itialized poin ters
  • All types of m em ory allocation an d free errors or m ism atches All types of m em ory allocation an d free errors or m ism atches
  • All types of m em ory leaks
  • Type m ism atches in global declaration s, poin ters, an d fun ction calls
  • Som e varieties of dead code (com pile-tim e) • Som e varieties of dead code (com pile tim e)

In sure++: Features

  Detection of m em ory corruption on heap an d stack Detection of un in itialized variables, poin ters, an d objects Detection of m em ory leaks an d other m em ory allocation / free errors y y / STL checkin g** for proper usage of STL con tain ers, an d related m em ory errors Com pile tim e checks for type an d size related errors Com pile-tim e checks for type- an d size-related errors Run tim e tracin g of fun ction calls GUI an d com m an d lin e in terface Mem ory error checkin g in 3rd party static an d dyn am ic libraries Direct in terfaces with Visual Studio debugger

  In sure++: Screen shot

  Buffer Overflow Protection Solution : Libsafe Solution : Libsafe

  Libsafe is a library which re-writes som e sen sitive libc fun ction s ( fun ction s ( strcpy, strcat, sprin tf, vsprin tf, getwd, gets, strcpy strcat sprin tf vsprin tf getwd gets

  realpath, fscan f, scan f, sscan f ) to preven t an y overflow

  caused by a m isuse of an y on e of them It laun ches alerts when an overflow attem pt is detected

  Libsafe in tercepts the calls to the un safe fun ction s an d uses its own im plem en tation of the fun ction in stead While keepin g the sam e sem an tic, it adds detection of the boun d violation s boun d violation s

  Com parin g Fun ction s of libc an d libsafe libsafe

  Som e fun ction s of libc are un safe because they do n ot check the boun ds of a buffer Im plem en tation of strcpy by libsafe: they do n ot check the boun ds of a buffer

  Im plem en tation of strcpy by libc: p e e a o o s cpy by bsa e

  char *strcpy(char *dest, const h * ) char *src) { ... if ((len = strnlen(src, max size)) == max size) char * strcpy(char * dest,const char *src) { max_size)) == max_size) _libsafe_die("Overflow caused by strcpy()"); real_memcpy(dest, src, len + 1); return dest; { char *tmp = dest; while ((*dest++ = *src++) != '\0') /* nothing */;

  The size of the dest buffer is n ot a factor for Fun ction libsafe_ die stops the process if

  return dest; } /* nothing */; return tmp; }

  The size of the dest buffer is n ot a factor for decidin g whether to copy m ore characters or n ot strlen return s m ax_ size (attem pt to buffer

  overflow) Sim ple Buffer Overflow in C

  Vuln erable C Program overrun .c

  #include <stdio.h> #include <stdio h> main() { char *name; char *dangerous_system_command; char *dangerous system command; name = (char *) malloc(10); dangerous_system_command = (char *) malloc(128); printf("Address of name is %d\n", name); printf("Address of name is %d\n" name); printf("Address of command is %d\n", dangerous_system_command); sprintf(dangerous_system_command, "echo %s", "Hello world!"); printf("What's your name?"); i tf("Wh t' ?") gets(name); system(dangerous_system_command); } }

  Code An alysis

  The first thin g the program does is declare two strin g variables an d assign m em ory to them h The " n a m e " variable is given 10 bytes of m em ory (which will allow it to hold a 10 - character strin g) character strin g)

  d a n ge ro u s _ s ys te m _ co m m a n d

  The " " variable is given 128 bytes

  You have to un derstan d that, in C, the m em ory chun ks given to these variables will be located directly n ext to each other in th e virtual m em ory space given to the program

  Code An alysis (con t’d) ~

  To com pile the overrun .c program ~

  Run this com m an d in Lin ux: R thi d i Li gcc overrun.c –o overrun [XX]$ ./overrun Address of name is 134518696 Address of command is 134518712 What's your name?xmen Hello world! [XX]$

  ~ "dangerous_system_command"

  The address given to the variable is 16 bytes from the start of the "n am e" variable

~ The extra 6 bytes are overhead used by the "m alloc" system call to

allow the m em ory to be return ed to gen eral usage when it is freed allow the m em ory to be return ed to gen eral usage when it is freed

Code An alysis (con t’d)

  The " ge ts ", which reads a strin g from the stan dard in put to the specified m em ory location , does n ot have a "len gth" specification

This m ean s it will read as m an y characters as it takes to get to the en d

of the lin e, even if it overrun s the en d of the m em ory allocated Kn owin g this, a attacker can overrun the " n a m e " m em ory in to the " d a n ge ro u s _ s ys te m _ co m m a n d " m em ory, an d run whatever com m an d he/ she wishes

  Code An alysis (con t’d) [XX]$ ./overrun Address of name is 134518696 Address of command is 134518712 What's your name?0123456789123456cat /etc/passwd root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin: daemon:x:2:2:daemon:/sbin: daemon:x:2:2:daemon:/sbin: adm:x:3:4:adm:/var/adm: lp:x:4:7:lp:/var/spool/lpd: sync:x:5:0:sync:/sbin:/bin/sync y y y shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown halt:x:7:0:halt:/sbin:/sbin/halt mail:x:8:12:mail:/var/spool/mail

What H appen ed Next

  Sin ce the project was run n in g behin d schedule, he had to hurry through testin g. hurry through testin g.

  Tim had worked with the sam e team for his previous projects, an d all of the other projects had successful projects, an d all of the other projects had successful con clusion s. Therefore, he thought that n othin g would possibly go wron g with this on e. This n otion m ade him overcon fiden t about the testin g of this project. But this tim e, he was n ot lucky. The web server of the clien t com pan y had succum bed to a buffer overflow attack. This was due to a flaw in codin g because boun ds were n ot checked. checked.

  Is Tim 's decision justified?

Sum m ary

  A buffer overflow occurs when a program or process tries to store m ore data in a buffer (tem porary data storage area) than it was in ten ded to hold d h d d h ld Buffer overflow attacks depen d on : the lack of boun dary testin g, an d a m achin e that can execute a code that resides in the data/ stack segm en t t d th t id i th d t / t k t Buffer overflow vuln erability can be detected by skilled auditin g of the code as well as boun dary testin g boun dary testin g Coun term easures in clude checkin g the code, disablin g stack execution , safer C library support, an d usin g safer com piler techn iques support an d usin g safer com piler techn iques Tools like stackguard, Im m un ix, an d vuln erability scan n ers help in securin g system s