Presentation is loading. Please wait.

Presentation is loading. Please wait.

Software Security Buffer Overflows. SECURITY INNOVATION ©2003 Common Programming Mistakes Poor design choices / assumptionsPoor design choices / assumptions.

Similar presentations

Presentation on theme: "Software Security Buffer Overflows. SECURITY INNOVATION ©2003 Common Programming Mistakes Poor design choices / assumptionsPoor design choices / assumptions."— Presentation transcript:

1 Software Security Buffer Overflows

2 SECURITY INNOVATION ©2003 Common Programming Mistakes Poor design choices / assumptionsPoor design choices / assumptions Failing to check user supplied inputFailing to check user supplied input Buffer overflowsBuffer overflows Incorrect levels and separation of privilegesIncorrect levels and separation of privileges Poor default settingsPoor default settings Predictable sources of randomnessPredictable sources of randomness Race conditionsRace conditions Poor failure modesPoor failure modes Insufficient testingInsufficient testing Failure to protect secrets properlyFailure to protect secrets properly Poor design reviewPoor design review Poor documentation and commentingPoor documentation and commenting Poor maintenance of legacy codePoor maintenance of legacy code Bad programming languagesBad programming languages

3 SECURITY INNOVATION ©2003 Buffer Overflow Attacks Internet (Morris) Worm of November 1988. The Internet Worm brought down more than 6000 sites by a little-known exploit called the buffer overflow. Collected host, network, and user information. Then broke into other machines using flaws present in those systems’ software. Flaws: –fingerd (no bounds checking). –sendmail (DEBUG command exploited).

4 SECURITY INNOVATION ©2003 Frequency of Buffer Overflow Attacks Total Number % of Total Exploits

5 SECURITY INNOVATION ©2003 Buffer Overflows Buffer overflows allow an attacker to overwrite parts of memory This can be used in two ways: –Overwriting security-related variables in memory –Overwriting the return address of a function, causing code inserted by the attacker to be executed

6 SECURITY INNOVATION ©2003 Buffer Overflow Attacks Also called: munging the stack, stack smashing, fandango on core, overrun screw, stack scribble and stale pointer. Exploit a lack of bounds checking on the size of input being stored in a buffer array. Attacker can make arbitrary changes to program state stored adjacent to the array. Commonly found in C programs. Why? –C lacks array bounds checking. –C programmers avoid error checking for performance reasons.

7 SECURITY INNOVATION ©2003 Finding buffer overflows If you have source code: find a local variable that does an unchecked copy into a buffer Library functions that perform unchecked copying: –gets() –strcpy() –strcat() –sprintf() –scanf() –…

8 SECURITY INNOVATION ©2003 Example: gets char *gets(char *s); Pointer to a character Reads texts from the standard input of a program, placing the first character at the location to which s points. Subsequent data are placed consecutively after s in memory. Bytes are read from standard input until the new line character or EOF is reached.

9 SECURITY INNOVATION ©2003 gets and Vulnerability In this function a programmer has no way to specify how big a buffer is being passed to gets. As a result if a real buffer is n bytes and an attacker tries to write n+m bytes into the buffer when running the program, the attack will always be successful, as long as the data does not include new lines.

10 SECURITY INNOVATION ©2003Continued.. char *gets(char *s); “This is white data. \n”Attack!! Attack!! data \n”

11 SECURITY INNOVATION ©2003 Risk with gets There are two significant risks in this case. First, variable adjacent in memory to the buffer can easily be overwritten. If such variable stores security critical data such as access control list, then an attacker can modify the data to great advantage. Second, the attacker will be able to trick the program into running arbitrary code.

12 SECURITY INNOVATION ©2003 Finding Buffer Overflows If you don’t have source code: try to make the program crash by feeding it very large input in all possible places

13 SECURITY INNOVATION ©2003 Buffer Overflows Overview: overwrite return address return address buffer … … shell code Create a string that: Contains shell code Overwrites return address to point to that shell code Program Stack

14 SECURITY INNOVATION ©2003 Buffer Overflows Overwrite return address –Lots of details to get right before it works: No nulls in (character-)strings Filling in the correct return address: –Attacker does not know the address of his own string –Fake return address must be precisely positioned Other overwritten data must not be used before return from function … –More information in “Smashing the stack for fun and profit” by Aleph One

15 SECURITY INNOVATION ©2003 Buffer Overflows Overwrite return address –Examples of shell-code strings: LINUX on Intel: 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"; SPARC Solaris: char shellcode[] = "\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\x91\xd0\x20\x08" "\x90\x1b\xc0\x0f\x82\x10\x20\x01\x91\xd0\x20\x08"; Windows: char shellcode[] = "\x55\x8B\xEC\x33\xFF\x57\xC6\x45\xFC\x63\xC6\x45“ “\xFD\x6D\xC6\x45\xFE\x64\x57\xC6\x45\xF8\x03" "\x80\x6D\xF8\x50" "\x8D\x45\xFC\x50\x90\xB8" "EXEC" "\xFF\xD0\x33\xC0\x50\x90” “\xB8" "EXIT" "\xFF\xD0\xC3";

16 SECURITY INNOVATION ©2003Scope Stack Overflows Simple EIP Attacks Linux X86 Beginner Intermediate Advanced

17 SECURITY INNOVATION ©2003Overview Basic O/S and Memory Concepts Stacks and Heaps Calling Convention C Variables & String Handling Vector and Payload Defeating Attacks

18 SECURITY INNOVATION ©2003 Basic Memory Concepts Processes programs started using exec() –Syscall Program gets virtual memory space –Entirely isolated –O/S Virtual Memory Management Memory addressed by word values (4 bytes) –0x00000000 – 0xffffffff –4 gb addressable

19 SECURITY INNOVATION ©2003 Executable Files Program file (PE) Windows (ELF) Linux –Many sections –Loaded into virtual address locations –Basic Section Types Data Text

20 SECURITY INNOVATION ©2003 The Heap Low in memory (0x8048000) Randomly accessed Mostly a VMM and O/S Concept Code and Data Sections “Process Space” Used For: –Long Term Storage –Large Data Storage

21 SECURITY INNOVATION ©2003 Yet More Heap Grows randomly –Yes, it really does –Considered to grow up Manually expanded –Malloc() –Brk()

22 SECURITY INNOVATION ©2003 Heap Continued

23 SECURITY INNOVATION ©2003 The Stack High in memory (0xbfffffff) FIFO Special CPU Registers (%esp) –CPU Understands Used For: –Function calling (parameters and saved regs) –Short term variables (C automatic variables)

24 SECURITY INNOVATION ©2003 The Stack Continued

25 SECURITY INNOVATION ©2003 More Stack – Get Used to It Grows down Randomly & FIFO accessed Instructions –Push –Pop Grows Automatically –Guard Pages

26 SECURITY INNOVATION ©2003 Memory usage In an IBM-PC, program code and data (usually) reside somewhere in the lower 640KB of system memory. 655359655359 00

27 SECURITY INNOVATION ©2003 Memory usage In an IBM-PC, program code and data (usually) reside somewhere in the lower 640KB of system memory. 655359655359 00 Program and Data 304359304359 350759350759

28 SECURITY INNOVATION ©2003 Memory usage Let’s examine the management of the data areas within the region assigned to the program. 655359655359 00 Program and Data 304359304359 350759350759

29 SECURITY INNOVATION ©2003 Memory usage The data area is composed of two regions. 350759350759 304359304359 Instructions

30 SECURITY INNOVATION ©2003 Memory usage The data area is composed of two regions. One is called the heap. 350759350759 304359304359 Instructions Heap

31 SECURITY INNOVATION ©2003 Memory usage The data area is composed of two regions. One is called the heap. The other is called the stack. 350759350759 304359304359 Instructions Heap Stack

32 SECURITY INNOVATION ©2003 Memory usage The heap contains things like static and external variables. 350759350759 304359304359 Instructions Heap Stack

33 SECURITY INNOVATION ©2003 Memory usage The stack contains things like automatic variables and function arguments. 350759350759 304359304359 Instructions Heap Stack

34 SECURITY INNOVATION ©2003 Memory usage As the program runs, the stack grows and shrinks towards the lower addresses. 350759350759 304359304359 Instructions Heap Stack

35 SECURITY INNOVATION ©2003 Memory usage For example, when a function is called, the stack grows. 350759350759 304359304359 Instructions Heap Stack

36 SECURITY INNOVATION ©2003 Memory usage For example, when a function returns to the calling program, the stack shrinks. 350759350759 304359304359 Instructions Heap Stack

37 SECURITY INNOVATION ©2003 Memory usage As the program runs, the heap grows and shrinks towards the higher addresses. 350759350759 304359304359 Instructions Heap Stack

38 SECURITY INNOVATION ©2003 Memory usage C++ allows you to allocate and free memory assigned to the heap. 350759350759 304359304359 Instructions Heap Stack

39 SECURITY INNOVATION ©2003 Some CPU Registers Important CPU Registers –EIP Effective Instruction Pointer Address of next Instruction –ESP Effective Stack Pointer Address of top of stack –EBP Base of stack for function Completely Optional

40 SECURITY INNOVATION ©2003 Calling Subroutines Many ways to jump from code to code –Jmp –Modify eip What about returning?

41 SECURITY INNOVATION ©2003 Calling Subroutines Again Two instructions –Call Push eip onto stack Jump to specified address –Ret Pop eip from stack Continue execution

42 SECURITY INNOVATION ©2003 Calling Convention Functions typically take arguments int sum(int a, int b); Calling Convention defines how Typically cdecl Push arguments onto the stack in reverse order

43 SECURITY INNOVATION ©2003 Example – Sum() 1.Push 0x00000003 onto stack – B 2.Push 0x00000002 onto stack – A 3.Call sum() Push eip onto stack Jump to sum() 4.Subroutine runs, return into eax 5.Ret eip popped from stack into eip

44 SECURITY INNOVATION ©2003 Stack Overflow Concept Saved eip is vulnerable Overwrite –Jump to arbitrary location on return

45 SECURITY INNOVATION ©2003Variables Automatic variables go onto stack In C: –Local variables –Auto keyword (storage class declaration) –Vmalloc()

46 SECURITY INNOVATION ©2003 C Example int example(int a, int b) { int temp; temp = a + b; return(temp); }

47 SECURITY INNOVATION ©2003 C Strings Null terminate character arrays Example: No defined length, determined by null

48 SECURITY INNOVATION ©2003 C String Handling Programs allocate buffers to parse strings in Typically local/automatic variables –Usually temporary –Malloc() is too much effort

49 SECURITY INNOVATION ©2003 C Example Stack

50 Beginner

51 SECURITY INNOVATION ©2003Beginner Most common data structure – the stack – “stack smashing attack”. 2 mutually dependent goals: –Inject Attack Code (attacker provides executable input string). –Change the Return Address (Buffer overflow changes the RA to point to the attack code). Which programs are attacked? –Usually, privileged services

52 SECURITY INNOVATION ©2003 Buffer Overflow Attacks 0xFFFFTop of Stack Attack Code Local Variables… buffer RA String Growth Stack Growth 0x0000 buffer Process Address Space

53 SECURITY INNOVATION ©2003 Example Illustrated argc user stack buffer large_string[128] RA Shellcode[] heap bss Process Address Space i long_ptr sfp

54 SECURITY INNOVATION ©2003 New C Example int parsestring(char *instring) { char buffer[100]; /* Save the string so we can chop it up */ strcpy(buffer, instring); /* Do some stuff here */ return(0); }

55 SECURITY INNOVATION ©2003 Sample Code Questions How long is the input string? How long is the buffer? What happens if we run off the end of the buffer?

56 SECURITY INNOVATION ©2003 Sample Code Answers If the user can affect create a long string they can escape the bounds of the buffer Overwrite saved EIP Ret causes jump to address overwritten

57 SECURITY INNOVATION ©2003 The Result (gdb) set args `perl -e "print 'A' x 120"` (gdb) run Starting program: a.out `perl -e "print 'A' x 120"` Program received signal SIGSEGV, Segmentation fault. 0x41414141 in ?? () (gdb)

58 SECURITY INNOVATION ©2003 Exploiting The Problem Attacker has control of EIP Need to jump to interesting code How do we inject code into the process? –Need to get it somewhere in the processes memory space –Place must be locatable

59 SECURITY INNOVATION ©2003 Exploiting The Problem Lots of options –Buffer itself –Environment Variables –Command Line Arguments First we’ll focus on in buffer code –Then explore more advanced methods

60 SECURITY INNOVATION ©2003 Payload Vs Insertion Vector The EIP overwrite is the Vector The code we jump to is the Payload The payload can do anything but must –Be Machine Code –Reasonably Small – Not contain Nulls (0x00) Payload often ‘shellcode’

61 SECURITY INNOVATION ©2003Shellcode \xeb\x1f jmp 0x1f // jump to call \x5e popl %esi // put “/bin/sh” add in esi \x89\x76\x08 movl %esi,0x8(%esi)// put esi in esi + 8 \x31\xc0 xorl %eax,%eax // eax = 0 \x88\x46\x07 movb %eax,0x7(%esi)// NULL terminate string \x89\x46\x0c movl %eax,0xc(%esi)// 4 byte NULL to esi +0xc(12) \xb0\x0b" movb $0xb,%al// put 0xb(11) in al \x89\xf3 movl %esi,%ebx// copy esi to ebx \x8d\x4e\x08 leal 0x8(%esi),%ecx// put add of esi+8 in ecx \x8d\x56\x0c leal 0xc(%esi),%edx// put add of esi+0xc(12) in edx \xcd\x80 int $0x80 // interrupt 80 (execve) \x31\xdb xorl %ebx,%ebx// ebx = 0 \x89\xd8 movl %ebx,%eax // eax = 0 \x40 inc %eax // eax += 1 \xcd\x80 int $0x80 // interrupt 80 (exit) \xe8\xdc\xff\xff\xff call -0x24 // call to 1 st intruction after jmp \x2f\x62\x69\x6e\x2f\x73\x68.string "/bin/sh"

62 SECURITY INNOVATION ©2003Example 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 large_string[128]; void main() { char buffer[96]; int i; long *long_ptr = (long *) large_string; /* long_ptr takes the address of large_string */ /* large_string’s first 32 bytes are filled with the address of buffer */ for (i = 0; i < 32; i++) *(long_ptr + i) = (int) buffer; /* copy the contents of shellcode into large_string */ for (i = 0; i < strlen(shellcode); i++) large_string[i] = shellcode[i]; /* buffer gets the shellcode and 32 pointers back to itself */ strcpy(buffer, large_string); }

63 SECURITY INNOVATION ©2003Problems What We Know –Length of buffer needed to overwrite save EIP What We Don’t Know –Where exactly on stack buffer will be Decided by environment So how can we define an EIP to jump to our code?

64 SECURITY INNOVATION ©2003Solutions We can make educated guess Modify payload to make remove need for accuracy

65 SECURITY INNOVATION ©2003Guessing In exploit program, we can determine %esp long getesp(void) { __asm__("movl %esp, %eax\n"); } Tells us typical stack location with libraries, environment etc Real address will be an offset from there (usually a negative offset)

66 SECURITY INNOVATION ©2003 NOP Sleds Payload can be anywhere in buffer –Or outside it! Place it at end NOPs before it Successfully jump to any of the NOPs, slide down sled to payload

67 SECURITY INNOVATION ©2003 Buffer Corruption Code not executed till function returns If the function modifies buffer the sled can be ruined int parsestring(char *instring) { char buffer[100]; strcpy(buffer, instring); buffer[30] = ‘A’; }

68 SECURITY INNOVATION ©2003 Avoiding Buffer Corruption Place payload somewhere safer –Environment variables –Other command line arguments –Another input field A Jump Sled –Sled consists of near jumps –Hoping to the payload

69 Intermediate

70 SECURITY INNOVATION ©2003 Attack Methodology Formalize the Attack Method Re-Use of Attack Code Separate the Deployment from the Payload Payloads can be chosen for desired effect Details and Restraints of both Payload and Deployment code

71 SECURITY INNOVATION ©2003Exploits A “BUG” in Software New bugs reported every day automated testing tools –USSR Labs “Exploit” is code that takes advantage of a bug in order to cause an effect

72 SECURITY INNOVATION ©2003 What can happen? Machine Crash kernel exception VIP process Application Crash (most common) Recoverable Exception Mobile Code (deadly) File Access (read or write) Denial of Service

73 SECURITY INNOVATION ©2003 Exploits Can be Grouped Some bugs are all the same Some bugs keep coming back –improper filtering –bounds checking –bad authentication –impersonation

74 SECURITY INNOVATION ©2003 Entry -vs- Effect The attack payload is not the same as the entry point Missile -vs- Warhead analogy The Delivery Mechanism can be decoupled from the Payload

75 SECURITY INNOVATION ©2003 Exploits Come in 2 Parts Injection Vector (deployment) –the actual entry-point, usually tied explicitly with the bug itself Payload (deployed) –usually not tied to bug at all - limited only by imagination. Some restraints.

76 SECURITY INNOVATION ©2003 Injection Vector Target Dependant OS Dependant Application Version Dependant Protocol Dependant Encoding Dependant

77 SECURITY INNOVATION ©2003Payload Independent of Injection Vector Still Depends on Machine, Processor, etc. With some exceptions Mobile Code, Just like a Virus Once established, can spread by any means –trust –scanning for more bugs

78 SECURITY INNOVATION ©2003Payload Denial of Service –use as launching point (arp spoofing) Remote Shell (common) –covert channel or ‘netcat’ like Worm/Virus –extremely dangerous Rootkit (common - stealth)

79 SECURITY INNOVATION ©2003 Injector/Payload Pairs One injector works on ‘n qualified hosts’ Example - IIS Injector works on ~20% of Web Hosts. Payload –Remote Shell for control –Shutdown Machine –Shutdown ALL Machines on subnet

80 SECURITY INNOVATION ©2003 Types of Injection Content Based –characters inserted into a data stream that result in the remote process doing something it shouldn’t. Process is still in control. Buffer Overflow –poor programming practice subverts architecture of code execution. Process loses control.

81 SECURITY INNOVATION ©2003 Types of Injection Trust Based –Boot virus/ Floppy/ CD (parasite process) –MACRO virus –Email Attachments (Melissa, etc) –Web Browsing (exploit user’s trust, etc) click thru

82 SECURITY INNOVATION ©2003 Do Governments Write Injector Code? 1995 US Defense Intelligence Agency Report –Cuban Military targets US w/ custom virii University of Havana, team of less than 20 computer experts –Russian KGB prior to 1991 coup attempt, KGB had virii intended to shut down US computers in times of war

83 SECURITY INNOVATION ©2003 Mobile Code in Global 2002? 1995 E&Y report –67% of companies hit bit virus 1996 E&Y report –63% of companies hit by virus 1996 UK Information Security Breaches Survey –51% of companies hit by virus

84 SECURITY INNOVATION ©2003 How Hard can it Hit? NCSA 1997 report –33% of all machines infected with virus –average cost of recovery ~$8000 US dollars November 1988 Morris Worm –strikes ~6,000 computers (10% of Internet at time) within hours –spreads via Buffer Overflow in fingerd –spreads via Sendmail exploit

85 SECURITY INNOVATION ©2003 How Hard can it Hit? 1989, “WANK” Worm –Hits NASA Goddard Space Center –spreads to US DOE High Energy Physics network (HEPNET) –2 weeks to clean all systems

86 SECURITY INNOVATION ©2003 The WANK Worm W O R M S A G A I N S T N U C L E A R K I L L E R S _______________________________________________________________ \__ ____________ _____ ________ ___ ____ __ _____/ \ \ \ /\ / / / /\ \ | \ \ | | | | / / / \ \ \ / \ / / / /__\ \ | |\ \ | | | |/ / / \ \ \/ /\ \/ / / ______ \ | | \ \| | | |\ \ / \_\ /__\ /____/ /______\ \____| |__\ | |____| |_\ \_/ \___________________________________________________/ \ / \ Your System Has Been Officically WANKed / \_____________________________________________/ You talk of times of peace for all, and then prepare for war.

87 Advanced

88 SECURITY INNOVATION ©2003 Buffer Overflow Injection Overflow the Stack Overflow the Heap Goal: Must control the value of the instruction pointer (processor specific) Goal: Get the Instruction Pointer to point to a user-controlled buffer.

89 SECURITY INNOVATION ©2003Challenges Injector/Payload size restrictions –tight coding requirements Injector and Payload in same buffer –cannot step on each other Guessing Address Values –sometimes called ‘offsets’ NULL characters, BAD characters –use encoding and stack tricks

90 SECURITY INNOVATION ©2003 Stack Injection Stack is used for execution housekeeping as well as buffer storage. Stack-based buffer must be filled in direction of housekeeping data. Must overwrite the housekeeping data

91 SECURITY INNOVATION ©2003 Address Housekeeping A B C D code heap IP DI SI FLAG SP BP stack IP

92 SECURITY INNOVATION ©2003 Stack Overflow 00 40 20 08 00 40 20 10 00 40 20 1C 00 40 20 14 00 40 20 18 00 40 20 1C EIP B u f f e r S p a c e C a n t W r i t e P a s t H e r e

93 SECURITY INNOVATION ©2003 The Problem with NULL STOPS 00 40 20 08 00 40 20 10 00 40 20 1C 00 40 20 14 00 40 20 18 00 40 20 1C x00 EIP ATTACK CODE

94 SECURITY INNOVATION ©2003 NULL must be PAST housekeeping data 00 40 20 08 00 40 20 0C 00 40 20 10 00 40 20 14 00 40 20 18 00 40 20 1C EIPOK

95 SECURITY INNOVATION ©2003 Little and Big Endian On Intel x86 (Little Endian), Values are stored ‘backwards’ - least significant byte goes first: 00 40 10 FF is stored as: FF 10 40 00

96 SECURITY INNOVATION ©2003 We Store Address in Housekeeping Data 00 40 21 04 00 40 21 00 00 40 20 0C 00 40 20 08 00 40 20 04 00 40 20 00 CD 68 45 7F Original Address New Address Allowable Buffer Space ATTACK CODE 0C 20 40 00

97 SECURITY INNOVATION ©2003 Injection is Complete We control the instruction pointer 04 21 40 00 New Address

98 SECURITY INNOVATION ©2003 Where to put the payload 00 40 21 04 00 40 21 00 00 40 20 0C 00 40 20 08 00 40 20 04 00 40 20 00 New Address EIP Allowable Buffer Space 04 21 40 00 ATTACK CODE

99 SECURITY INNOVATION ©2003 Confined Payload Byte Compression Use only preloaded functions –Payload doesn’t need to build jumptables –Useable functions must be loaded Use Hardcoded addresses –Payload designed for a specific process with predictable features Data portion of payload needs to be small

100 SECURITY INNOVATION ©2003 Using More Stack for Payload NULL OK 77 40 20 08 77 40 20 0C 77 40 20 10 77 40 20 14 77 40 20 18 77 40 20 1C EIP Allowable Buffer Space ATTACK CODE 0D 45 68 77 No NULL in Address

101 SECURITY INNOVATION ©2003 Much Larger Payload Allowable Buffer Space EIP New EIP Available Payload Area

102 SECURITY INNOVATION ©2003 When Does the Address Contain a NULL Character Lowland Address - starts with 00 –stack is in lowland on Windows NT usually 00 40 XX XX –limits size of payload Highland Address - no zeros in address –stack is in highland under Linux –unlimited payload size

103 SECURITY INNOVATION ©2003 Large Payload, Lowland Address We cannot use a lowland address directly, because it limits our payload We can use a CPU register We can use stack values that remain undamaged

104 SECURITY INNOVATION ©2003 A Register Points to the Stack A B C D code heap IP DI SI FLAG SP BP stack IP

105 SECURITY INNOVATION ©2003 Call thru a Register Call eax, call ebx, etc –FF D0 = call eax –FF D3 = call ebx –FF D1 = call ecx –etc, etc

106 SECURITY INNOVATION ©2003 Push a Register then Return Push register –push eax = 50 –push ebx = 53 –etc Then RET –RET = C3

107 SECURITY INNOVATION ©2003 Guessing Where Do We Want to Go Today We jump to the wrong address –crashes software –payload doesn’t execute Use NOP (no-op) - a single byte instruction –NOP = 90 Fill buffer with NOP’s –“NOP Sled”

108 SECURITY INNOVATION ©2003 NOP Sled Allowable Buffer Space Start of Payload Slide up to payload New EIP NOP Sled

109 SECURITY INNOVATION ©2003 Your own VTABLE The VTABLE has addresses for all virtual functions in the class. This usually includes a destructor - which will be called when the object is destroyed (deallocated from memory) Overwrite any function that works

110 SECURITY INNOVATION ©2003 Injection is Complete Kernel level overflows all over in NT Off by one errors causing frame pointer overwrite Multi-stage attacks where you must first get the target into a state before attempting overflow The effects of URL or MIME encoding

111 SECURITY INNOVATION ©2003 Now for the Payload Using Loaded Functions Encoding our own data Loading new functions & DLL’s Making a shell

112 SECURITY INNOVATION ©2003 The Payload Real Code DATA NOP Sled

113 SECURITY INNOVATION ©2003 Remote Command Shell Spawn a process –CreateProcessA (kernel32 function) –INT 80 (linux) (execve syscall) Pipe the output thru socket –Named pipes (~5 functions) –Connect in or out over any TCP socket

114 SECURITY INNOVATION ©2003 Covert Channel If exploited process is root or SYSTEM –TDI or NDIS hook –session over ACK packets or ICMP IIS –Patch any point where URL requests are handled –no kernel required

115 SECURITY INNOVATION ©2003WORMS Payload searches for new hosts to attack Trust Exploitation –sniff passwords on wire –SMB sessions to other NT hosts –NT Registry Alteration –NFS/Drive Sharing Ability to build survivability into Payload –what % of hosts are eligible?

116 SECURITY INNOVATION ©2003 Interrupt Life Cycle Worm will die if certain condition is not met Existance of File Existance of Network Entity Floppy in floppy drive (testing lab)

117 SECURITY INNOVATION ©2003 Other Stack / Heap Attacks Heap Overflows –Interesting area Format strings

118 SECURITY INNOVATION ©2003 Attack Summary Injection is not the same as payload Payloads can perform –Denial of Service –WORM –Remote Shell –Rootkit

119 SECURITY INNOVATION ©2003 Attack Summary Injection has many challenges –NULL characters –Stack size –Highland/Lowland address –Calling thru CPU registers

120 SECURITY INNOVATION ©2003 Attack Summary Filters limit what we can use in a payload Limited OP-CODE sets can still be used to build fully functional programs

121 SECURITY INNOVATION ©2003 Attack Summary Our payload is encoded We can build jumptables We can load new DLL’s and Functions We can hard-code addresses or load them dynamically We can use Lysine Deficiency to keep Worms from spreading uncontrolled

122 SECURITY INNOVATION ©2003 Solutions to Buffer Overflow Attacks Static –Centralized Modification of systems libraries and/or an operating system kernel. –DeCentralized Modification of privileged programs and/or C programming language compilers. –LINT-like tools. –Range Analysis and Constraint Analysis. –Rational Purify –Program Verification e.g., ESC. Dynamic –StackGuard, StackShield. –Type Safe Languages: e.g., Java

123 SECURITY INNOVATION ©2003StackGuard A compiler extension that enhances executable code produced by the compiler. Detects and thwarts buffer-overflow attacks against the stack. Transparent to the normal function of programs.

124 SECURITY INNOVATION ©2003StackGuard Prevents changes to active RAs in 2 ways: 1.By detecting change of the RA before the function returns. (more efficient and portable). 2.By completely preventing the write to the RA (more secure). Canary Word Next to Return Address Top of Stack Return Address Canary Word Local Variables… buffer0xffff0x0000 Stack Growth String Growth

125 SECURITY INNOVATION ©2003 StackGuard - Detecting RA Change Before Return Detection done before a function returns. A canary word placed next to the RA on the stack. When function returns, it first checks to see that the canary word is intact before jumping to the RA pointed word. Key: RA is unaltered iff the canary word is unaltered. (How?) – true for buffer overflow attacks.

126 SECURITY INNOVATION ©2003 StackGuard - Detecting RA Change Before Return StackGuard implementation - simple patch to gcc gcc function_prologue and function_epilogue functions - altered to emit code to place and check canary words. Problem: Attackers can develop buffer overflows insensitive to StackGuard. Solution: Randomize the Canary.

127 SECURITY INNOVATION ©2003 Defeating Stackguard Need to use overflow to overwrite a pointer that is later used to set a location to a value we can specify Can use this to overwrite –Got table entries (exit() springs to mind) –Fnlist[] array of atexit() function pointers

128 SECURITY INNOVATION ©2003MemGuard MemGuard: used to protect an RA when a function is called, & unprotect the RA when the function returns. Adaptive Defense Strategies Function Prologue Code: Protecting the Return Address With MemGuard push a push b move 164 into a move arg[0] into b trap 0x80 pop b pop a

129 SECURITY INNOVATION ©2003 Automated Detection of Buffer Overrun Vulnerabilities Involves a synthesis of ideas from program analysis, theory, and systems security. Main Idea: to apply standard static analysis techniques. Formulate the buffer overrun detection problem as an integer constraint problem. Use some simple graph theoretic techniques to construct an efficient algorithm for solving the integer constraints.

130 SECURITY INNOVATION ©2003 Automated Detection of Buffer Overrun Vulnerabilities Security knowledge is used to formulate heuristics then these are used to capture the class of security-relevant bugs that tend to occur in real programs. Aim for scalability at the cost of precision. Reason : to analyze large programs – like sendmail. Result: Some false negatives and false positives.

131 SECURITY INNOVATION ©2003 Automated Detection of Buffer Overrun Vulnerabilities Early experience with prototype –Linux net tools –Sendmail 8.9.3 –Sendmail 8.7.5 Performance –Sub-optimal but usable. –Scalable. Limitation: Large number of false alarms due to imprecision in the range analysis.

132 SECURITY INNOVATION ©2003 Rational Purify A tool that developers and testers are using to find memory leaks and access errors. Detects the following at the point of occurrence: –reads or writes to freed memory. –reads or writes beyond an array boundary. –reads from uninitialized memory. Upon demand, employs a garbage detector to find and identify existing memory leaks. Purify finds run-time-detectable errors.

133 SECURITY INNOVATION ©2003 Detecting Memory Access Errors Purify "traps" every memory access a program makes (other than instruction fetch) maintains and checks a state code for each byte of memory Accesses inconsistent with the current state –diagnostic message printed –function CATCH_ME called inserts a function call instruction directly into a program's object code, before every load or store The functions called maintain a bit table that holds a 2-bit state code for each byte in the heap, stack, data, and bss sections

134 SECURITY INNOVATION ©2003 Purify - Catching Array Bounds Violations To catch array bounds violations, Purify allocates a small "red-zone" at the beginning and end of each block returned by malloc. The bytes in the red-zone are recorded as unallocated. If a program accesses these bytes, Purify signals an array bounds error.

135 SECURITY INNOVATION ©2003 Technical Solutions - OpenWall Solar Designer Among other things –Non executable stack Not a problem with return into libc –Mmaps Libc to an address including 0x00 Can’t pass arguments, since buffer ends

136 SECURITY INNOVATION ©2003 Defeating Openwall Use Global Offset Table Functions Works well if program maps any useful functions

137 SECURITY INNOVATION ©2003Solutions Programming problem Easy to miss Strcpy, sprintf, strcat etc. don’t make it any easier

138 SECURITY INNOVATION ©2003 Ultimate Solution Bounds Checking –Major processing impact Second best, remove strcpy, strcat etc from libc –Breaks almost every program in existence

139 SECURITY INNOVATION ©2003 Solutions to Buffer Overflow Attacks Eliminate Use of Vulnerable C functions FunctionSuitable Replacement gets()fgets() sprintf() strcat()strncat() strcpy()strncpy() streadd() strtrns() index() vsprintf() fscanf() scanf() getopt() getpass() realpath()

140 SECURITY INNOVATION ©2003Conclusion Buffer overflows are a very powerful cracker tool Buffer overflow attacks are easy to incorporate in “attack script” that can be used by “script kiddies” Buffer overflow vulnerabilities are always created by the programmer

141 SECURITY INNOVATION ©2003Conclusion To prevent buffer overflows: –Use Java (or another type-safe language) But: The VM may contain vulnerabilities –Defensive programming –Static analysis tools –Disallowing executable code on the stack –Compiler support

142 SECURITY INNOVATION ©2003 A Few Documents on Buffer Overflows There are hundreds! "Smashing The Stack For Fun and Profit" written by "Aleph One”, Phrack magazine in November of 1996. "How to Write Buffer Overflows" by "Mudge" released in 1997. "Stack Smashing Vulnerabilities in the UNIX Operating System" by Nathan P. Smith. also released in 1997. "The Tao of Windows Buffer Overflows" by "DilDog," April of 1998.

143 The Java Solution

144 SECURITY INNOVATION ©2003 Type-Safe Languages - Java Buffer Overrun problem – due to lack of type safety in C. Type-safety is one of the foundations of the Java security model. Java Security Goals –programs should be: –Safe from malevolent programs –Non-intrusive –Authenticated

145 SECURITY INNOVATION ©2003 Java Security –Encrypted –Audited –Well-defined –Verified –Well-behaved –C2 or B1 certified Ability to download programs over the network and run them on another machine within the context of a Java enabled browser.

146 SECURITY INNOVATION ©2003 The Java Sandbox Java SandBox - provides an environment on the computer where the program can play but confined within certain bounds. Local or remote code Codes run with different permissions No built-in notion of trusted code sandbox JVM Security PolicyClass Loader Valuable resources

147 SECURITY INNOVATION ©2003 The Java Sandbox Minimal Sandbox - Access to CPU, screen, keyboard, and mouse, and to its own memory. Default Sandbox - Access to CPU and its own memory as well as access to the web server from which it was loaded. Access to CPU, its memory, its web server, and to a set of program-specific resources. Open Sandbox – access to all resources.

148 SECURITY INNOVATION ©2003 Anatomy of a Java Application Signed Class Files Core API Class Files Remote Class Files Local Class Files Core Java API Security Package Bytecode Verifier Class Loader Security Manager Access Controller Operating System Key Database

149 SECURITY INNOVATION ©2003 Java Language Security Java Language Security Constructs –every primitive data element has an access level associated with it which can be: Private Default (or package) Protected Public Credit Card example - and

150 SECURITY INNOVATION ©2003Rules Access methods are strictly adhered to. Programs cannot access arbitrary memory locations. Entities that are declared as final must not be changed. Variables may not be used before they are initialized. Array bounds must be checked on all array accesses. Objects cannot be arbitrarily cast into other objects.

151 SECURITY INNOVATION ©2003 Enforcement of Rules Done at 3 different times –Compile time –Link time –Runtime The Bytecode Verifier Mini-Theorem Prover proves: –Class file has correct format. – final classes not subclassed Bytecode Verifier Class Loaded Class Object Methods Bytecodes

152 SECURITY INNOVATION ©2003 Enforcement of Rules – final methods not overridden. –Every class has a single superclass. –No illegal data conversion of primitive data types (e.g., int to Object). –No illegal data conversion of objects occurs. –No operand stack overflows or underflows. Runtime Enforcement –Array bounds checking (done by the VM) –Object casting

153 SECURITY INNOVATION ©2003 The Class Loader Initially, only the class loader knows certain information about classes that have been loaded into the virtual machine. Only the class loader knows where a particular class originated. Only the class loader knows whether or not a particular class was signed.

154 SECURITY INNOVATION ©2003 Class Loader Class Loaders and Security Enforcement Class Loaders and Namespaces Anatomy of a Class Loader –The Internal Class Loader (from files) –The Applet Class Loader –The RMI Class Loader –The Secure Class Loader (protection domain) –The URL Class Loader (HTTP)

155 SECURITY INNOVATION ©2003 Security Manager Ultimately responsible for determining most of the parameters of the Java sandbox. Ultimately determines whether operations should be permitted or rejected. Trusted Classes (loaded by core API) Untrusted Classes (loaded from a class loader). Signed classes (trusted). An untrusted class cannot directly connect to the database server Network Browser

156 SECURITY INNOVATION ©2003 Access Controller Decides whether access to a critical system resource should be permitted or denied. Code Source. Permissions. Policies. Protection Domains.

157 SECURITY INNOVATION ©2003 Malicious Applets 3 classes of attacks –Denial of service –Invasion of privacy –Annoyance Collections on the web Easy and common

158 SECURITY INNOVATION ©2003 Attack Applets At least 15 serious security bugs Major news when discovered Result in full system penetration

159 SECURITY INNOVATION ©2003 Java Concerns ATTACK CLASS EXPLANATION AND CONSEQUENCES JAVA DEFENSE System Modification The most severe class of attacks. Applets that implement such attacks are attack applets. Consequences of these attacks: severe. Strong Invasion of Privacy If you value your privacy, this attack class may be particularly odious. They are implemented by malicious applets. Include mail forging. Consequences of these attacks: moderate. Strong Denial of Service Also serious but not severely so, these attacks can bring a machine to a standstill. Also implemented by malicious applets. May require reboot. Consequences of these attacks: moderate. Weak Antagonism Merely annoying, this attack class is the most commonly encountered. Implemented by malicious applets. May require restart of browser. Consequences of these attacks: light to moderate. Weak

160 SECURITY INNOVATION ©2003 Hostile Applets Examples of Hostle applets – - program tells you have a security problem, you need to restart, when you do it sends your username and password to the initiator, then crashes your PC. – kills any applets on your PC and any other applets that you download. – Bombards your monitor with black screens so that you don’t know what actions you are taking, while it screams like a banshee. – very popular, forces you to visit the same website over and over again opening a new window each time.

161 Race Conditions

162 SECURITY INNOVATION ©2003 Race Conditions Occur when multiple processes interfere with each other; an attacker may be able to exploit this condition Races can be between secure program processes, or with an attacker’s process

163 SECURITY INNOVATION ©2003 Requirements for Race Condition: Two or more processes have access to the same object Algorithm (etc) used by processes doesn't properly enforce an access order At least one process modifies the object

164 SECURITY INNOVATION ©2003 Searching for Race Conditions in File Access (TOCTTOU) Define Function Groups (check group; use group) Find All Such functions in call graphs Find Paths from Functions that call check functions to functions that call use functions. Print locations and paths to illustrate problem

165 SECURITY INNOVATION ©2003 Simple Race Condition

166 SECURITY INNOVATION ©2003 Effects of Race Conditions Normally: –race conditions show up as periodic errors – frequency of the error will depend upon how likely the 'bad' order is to occur – it is often hard to get race condition errors to repeat When exploited: –crackers can attempt to force the particular conditions that will produce a flaw –depending upon the exact form of the flaw, it may be produced with high probability – most common (mis)use: modify the value of some shared object

167 SECURITY INNOVATION ©2003 Race Conditions Example: Print server race condition with print quotasPrint server race condition with print quotas –User prints file –Print server determines cost of file –Print server checks account balance and deducts amount –Print server spools file for printing Attack: lpr smallfile sleep (1) cat bigfile > smallfile

168 SECURITY INNOVATION ©2003 Race Conditions A race condition attack exploits the fact that multiple instruction transactions are not atomicA race condition attack exploits the fact that multiple instruction transactions are not atomicExample: Race condition in the old UNIX “mkdir” commandRace condition in the old UNIX “mkdir” command –mkdir executed with two Stages: Storage allocatedStorage allocated Ownership transferred to userOwnership transferred to user Attack: –User initiates mkdir –User quickly replaces the new directory with /etc/passwd –mkdir process transfers ownership to user Many such problems have existed with temporary files in /tmpMany such problems have existed with temporary files in /tmp

169 SECURITY INNOVATION ©2003 Example: mkdir. mkdir is actually a fairly complex sequence of actions. Here are some of the actions triggered by mkdir dir under an early implementation for a Unix system: –Super user creates a directory object dir. –Permissions are set to 777. – Superuser does a chown to change the ownership of the directory to calling user. – Modify permissions via umask(2) to match the environment umask value. Can you spot the problem??

170 SECURITY INNOVATION ©2003 One difficulty... One difficulty... From the man pages: – The mkdir command creates specified directories in mode 777. The directories are then modified by umask(2), according to how you have set up umask. Patient crackers can automate a process to exploit this race condition to obtain ownership of file. Here's a well-known method: – Find a writable directory – Start a scanning program that will look for creation of /tmp/junk. – Start up mkdir /tmp/junk and use nice to cause it to run slowly in the background. Move scanner to foreground.

171 SECURITY INNOVATION ©2003 Flaw continued... Flaw continued... When the scanner spots the new directory: – Remove the original /tmp/junk – Create a link from the secret file you want to /tmp/junk. Suppose the scanner's link in (2) beat the mkdir's chown. mkdir will now change the ownership of the secret file to cracker.

172 SECURITY INNOVATION ©2003 Why do these problems arise? Problem: there are many of these race conditions in operating systems. Many occur in common system utilities. –It is a lot of trouble to identify and then fix them. Often the fix will cause systems to run slower, since it is necessary to coordinate access. Most sites don't have anyone with the time or ability to do so properly. The above explains why it is important that all users of a system be trustworthy.

173 SECURITY INNOVATION ©2003 Another example Aside: not all race conditions are in software. Here's an old hardware problem mentioned on alt.hacker: – The vending machines at school allows you to charge snacks to your student ID. First, you run your ID through a magnetic scanner and then the machine connects to a server (through a phone jack in the back) and checks to see if you have any credit. Once your ID clears, you simply unplug the jack, click on Snickers, and un/re-plug the machine.

174 SECURITY INNOVATION ©2003 Avoiding "access" race conditions Suppose we want to write a SUID-root program that does the following: –Creates file –Changes ownership to the invoker –Writes to the file Naive approach: –create file, chown, chmod, write.

175 SECURITY INNOVATION ©2003 Race Condition Analysis TOCTOU (Time Of Check and Time Of Use) functions are classified based on their handler into functions that can be checks and functions that can be uses Every time this kind of function is found the identifier that holds the file name is checked and a mapping variable is stored to the list of TOCTOU functions that use that variable.

176 SECURITY INNOVATION ©2003 Timing Attacks Timing attacks extract secret information based on the time a device takes to respond. Applicable to: –Smartcards –Cell phones –PCI cards –Network software Examples:Examples: –RSA exponentiation –Password checking and lengths –Inter-keystroke timing (e.g. attack on ssh)

177 SECURITY INNOVATION ©2003 Timing Attacks Consider the following pwd checking code:Consider the following pwd checking code: int password-check( char *inp, char *pwd) { if (strlen(inp) != strlen(pwd)) return 0; for( i=0; i < strlen(pwd); ++i) if ( inp[i] != pwd[i] ) return 0; return 1; } A simple timing attack will expose the length and the password one character at a time.A simple timing attack will expose the length and the password one character at a time.

178 SECURITY INNOVATION ©2003 Timing Attacks Correct code:Correct code: int password-check( char *inp, char *pwd){ oklen = 1; if (strlen(inp) != strlen(pwd)) oklen=0; for( ok=1, i=0; i < strlen(pwd); ++i) if ( inp[i] != pwd[i] ) ok = ok & 0; else ok = ok & 1; return ok & oklen; } Timing attack is ineffective.Timing attack is ineffective.

Download ppt "Software Security Buffer Overflows. SECURITY INNOVATION ©2003 Common Programming Mistakes Poor design choices / assumptionsPoor design choices / assumptions."

Similar presentations

Ads by Google