program security part 2

71
Program Security Program Security Part 2 Part 2 Trying to Prevent Trying to Prevent Attacks Due to Attacks Due to Insecure Code Insecure Code

Upload: alban

Post on 01-Feb-2016

48 views

Category:

Documents


0 download

DESCRIPTION

Program Security Part 2. Trying to Prevent Attacks Due to Insecure Code. Assessing the Impact of Memory Corruption. Let's try to access the risk these memory corruption vulnerabilities represent. A number of factors affect how exploitable a vulnerability is. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Program Security Part 2

Program SecurityProgram SecurityPart 2Part 2

Trying to Prevent Attacks Due Trying to Prevent Attacks Due to Insecure Codeto Insecure Code

Page 2: Program Security Part 2

22

Assessing the Impact of Memory Corruption Assessing the Impact of Memory Corruption

Let's try to access the risk these memory Let's try to access the risk these memory corruption vulnerabilities represent.corruption vulnerabilities represent.

A number of factors affect how exploitable a A number of factors affect how exploitable a vulnerability is.vulnerability is.

By being aware of these factors, code auditors By being aware of these factors, code auditors can estimate how serious a vulnerability is and can estimate how serious a vulnerability is and the extent to which it can be exploited.the extent to which it can be exploited.

Can it be used to crash the application?Can it be used to crash the application? Can arbitrary code be run?Can arbitrary code be run?

Page 3: Program Security Part 2

33

Assessing the Impact of Memory CorruptionAssessing the Impact of Memory Corruption

The only way to know for certain is to write a The only way to know for certain is to write a proof-of-concept exploit, but that approach can proof-of-concept exploit, but that approach can be far too time consuming for even a moderate-be far too time consuming for even a moderate-sized application assessment.sized application assessment.

Instead, we can reasonably estimate Instead, we can reasonably estimate exploitability by answering a few questions exploitability by answering a few questions about the resulting memory corruption.about the resulting memory corruption.

This approach is not as definitive as a proof-of-This approach is not as definitive as a proof-of-concept exploit, but it's far less time consuming, concept exploit, but it's far less time consuming, making it adequate for most assessments.making it adequate for most assessments.

Page 4: Program Security Part 2

44

The Real Cost of Fixing VulnerabilitiesThe Real Cost of Fixing Vulnerabilities

Indeed history has shown that attackers and Indeed history has shown that attackers and security researches alike have come up with security researches alike have come up with ingenious ways to exploit the seemingly ingenious ways to exploit the seemingly unexploitable.unexploitable.

Therefore, most auditors think that software Therefore, most auditors think that software vendors should treat all issues as high priority, vendors should treat all issues as high priority,

Page 5: Program Security Part 2

55

The Real Cost of Fixing VulnerabilitiesThe Real Cost of Fixing Vulnerabilities

You might be surprised at the amount of resistance You might be surprised at the amount of resistance you can encounter when disclosing vulnerabilities you can encounter when disclosing vulnerabilities to vendors - even vendors who specifically hired to vendors - even vendors who specifically hired you to perform an assessment.you to perform an assessment.

Vendors often say that potential memory corruption Vendors often say that potential memory corruption bugs aren't exploitable or aren't problems for some bugs aren't exploitable or aren't problems for some reason or another.reason or another.

However, memory corruption affects an application However, memory corruption affects an application at its most basic level, so all instances need to be at its most basic level, so all instances need to be given serious consideration.given serious consideration.

Page 6: Program Security Part 2

66

Protection MechanismsProtection Mechanisms The attack basics covered so far represent The attack basics covered so far represent

viable exploitation techniques for some viable exploitation techniques for some contemporary systems, but the security contemporary systems, but the security landscape is changing rapidly.landscape is changing rapidly.

Modern operating systems often include Modern operating systems often include preventive technologies to make it difficult to preventive technologies to make it difficult to exploit vulnerabilities such as buffer overflows.exploit vulnerabilities such as buffer overflows.

These technologies typically reduce an These technologies typically reduce an attacker's chance of exploiting a bug or at least attacker's chance of exploiting a bug or at least reduce the chance that a program can be reduce the chance that a program can be constructed to reliably exploit a bug on a target constructed to reliably exploit a bug on a target host.host.

Page 7: Program Security Part 2

77

Protection MechanismsProtection Mechanisms We'll focus on technical details of common We'll focus on technical details of common

anticorruption protections and address potential anticorruption protections and address potential and real weaknesses in these mechanisms.and real weaknesses in these mechanisms.

This discussion isn't a comprehensive study of This discussion isn't a comprehensive study of protection technologies, but it does touch on the protection technologies, but it does touch on the most commonly deployed ones.most commonly deployed ones.

For each protection technology, we'll also For each protection technology, we'll also consider the limitations of the technology since consider the limitations of the technology since unfortunately, there are also limitations.unfortunately, there are also limitations.

Page 8: Program Security Part 2

88

Heap Implementation HardeningHeap Implementation Hardening

Recall that heap overflows are typically exploited Recall that heap overflows are typically exploited through the unlinking operations performed by the through the unlinking operations performed by the system's memory allocation and deallocation system's memory allocation and deallocation routines.routines.

The list operations in memory management routines The list operations in memory management routines can be leveraged to write to arbitrary locations in can be leveraged to write to arbitrary locations in memory and seize complete control of the memory and seize complete control of the application.application.

In response to this threat, a number of systems have In response to this threat, a number of systems have hardened their heap implementations to make them hardened their heap implementations to make them more resistant to exploitation.more resistant to exploitation.

Page 9: Program Security Part 2

99

Heap Implementation HardeningHeap Implementation Hardening

Windows XP SP2 and later have implemented various Windows XP SP2 and later have implemented various protections to ensure that heap operations don't protections to ensure that heap operations don't inadvertently allow attackers to manipulate the process inadvertently allow attackers to manipulate the process in a harmful manner.in a harmful manner.

These mechanisms include the following:These mechanisms include the following: An 8-bit cookie is stored in each heap header structure.An 8-bit cookie is stored in each heap header structure.

An XOR operation combines this cookie with a global heap An XOR operation combines this cookie with a global heap cookie, and the heap chunk's address divided by 8.cookie, and the heap chunk's address divided by 8.

If the resulting value is not 0, heap corruption has occurred.If the resulting value is not 0, heap corruption has occurred. Because the address of the heap chunk is used in this Because the address of the heap chunk is used in this

operation, cookies shouldn't be vulnerable to brute force operation, cookies shouldn't be vulnerable to brute force attacks.attacks.

Page 10: Program Security Part 2

1010

Heap Implementation HardeningHeap Implementation Hardening Checks are done whenever an unlink operation occurs Checks are done whenever an unlink operation occurs

to ensure that the previous and next elements are to ensure that the previous and next elements are indeed valid.indeed valid. Specifically, both the next and previous elements Specifically, both the next and previous elements

must point back to the current element about to be must point back to the current element about to be unlinked.unlinked.

If they don't, the heap is assumed to be corrupt and If they don't, the heap is assumed to be corrupt and the operation is aborted.the operation is aborted.

The UNIX glibc heap implementation has also The UNIX glibc heap implementation has also been hardened to prevent easy heap exploitation.been hardened to prevent easy heap exploitation.

The glibc developers have added unlink checks to The glibc developers have added unlink checks to their heap management code, similar to the their heap management code, similar to the Windows SP2 defenses.Windows SP2 defenses.

Page 11: Program Security Part 2

1111

Limitations of Heap Implementation HardeningLimitations of Heap Implementation Hardening

Note that if a Windows user fails to install SP2, Note that if a Windows user fails to install SP2, this protection is not implemented.this protection is not implemented.

Unfortunately, many users fail to install patches.Unfortunately, many users fail to install patches. Heap protection technologies aren't perfect.Heap protection technologies aren't perfect. Most have weaknesses that still allow attackers Most have weaknesses that still allow attackers

to leverage heap data structures for reliable (or to leverage heap data structures for reliable (or relatively reliable) exploitation.relatively reliable) exploitation.

There are several published works on defeating There are several published works on defeating both Windows and UNIX heap protections.both Windows and UNIX heap protections.

Page 12: Program Security Part 2

1212

Limitations of Heap Implementation HardeningLimitations of Heap Implementation Hardening

Some published works on defeating both Some published works on defeating both Windows and UNIX heap protections:Windows and UNIX heap protections: "Defeating Microsoft Windows XP SP2 Heap "Defeating Microsoft Windows XP SP2 Heap

Protection and DEP ByPass" by Alexander Anisimov Protection and DEP ByPass" by Alexander Anisimov http://www.maxpatrol.com/defeating-xpsp2-heap-http://www.maxpatrol.com/defeating-xpsp2-heap-protection.htmprotection.htm

"A New Way to Bypass Windows Heap Protections" "A New Way to Bypass Windows Heap Protections" by Nicholas Falliere by Nicholas Falliere http://www.securityfocus.com/infocus/1846/http://www.securityfocus.com/infocus/1846/

"Windows Heap Exploitation" by Oded Horovitz and "Windows Heap Exploitation" by Oded Horovitz and Matt Connover Matt Connover http://www.cybertech.net/~sh0ksh0k/heap/XPSP2%2http://www.cybertech.net/~sh0ksh0k/heap/XPSP2%20Heap%20Exploitation.ppt0Heap%20Exploitation.ppt

Page 13: Program Security Part 2

1313

Limitations of Heap Implementation HardeningLimitations of Heap Implementation Hardening UNIX glibc implementations have undergone similar UNIX glibc implementations have undergone similar

scrutiny.scrutiny. One useful resource is "The Malloc Maleficarum" by One useful resource is "The Malloc Maleficarum" by

Phantasmal Phantasmagoria Phantasmal Phantasmagoria http://www.securityfocus.com/archive/1/413007/30/0/thttp://www.securityfocus.com/archive/1/413007/30/0/threadedhreaded

The most important limitation of these heap protection The most important limitation of these heap protection mechanisms is that they protect only the internal heap mechanisms is that they protect only the internal heap management structures.management structures.

They don't prevent attackers from modifying They don't prevent attackers from modifying application data on the heap.application data on the heap.

If you are able to modify other meaningful data, If you are able to modify other meaningful data, exploitation is usually just a matter of time and effort.exploitation is usually just a matter of time and effort.

Page 14: Program Security Part 2

1414

Limitations of Heap Implementation HardeningLimitations of Heap Implementation Hardening

Modifying program variables is difficult, however, Modifying program variables is difficult, however, as it requires specific variable layouts.as it requires specific variable layouts.

An attacker can create these layouts in many An attacker can create these layouts in many applications, but it isn't always a reliable form of applications, but it isn't always a reliable form of exploitation - especially in multithreaded exploitation - especially in multithreaded applications.applications.

Another point to keep is mind is that it is not Another point to keep is mind is that it is not uncommon for applications to implement their uncommon for applications to implement their own memory management strategies on top of own memory management strategies on top of the system allocation routines.the system allocation routines.

Page 15: Program Security Part 2

1515

Limitations of Heap Implementation HardeningLimitations of Heap Implementation Hardening

In this situation, the application in question In this situation, the application in question usually requests a page or series of pages from usually requests a page or series of pages from the system at once and then manages them the system at once and then manages them internally with its own algorithm.internally with its own algorithm.

This can be advantageous for attackers because This can be advantageous for attackers because custom memory management algorithms are custom memory management algorithms are often unprotected, leaving them vulnerable to often unprotected, leaving them vulnerable to variations on classic heap overwrite attacks.variations on classic heap overwrite attacks.

Page 16: Program Security Part 2

1616

Nonexecutable Stack And Heap ProtectionNonexecutable Stack And Heap Protection

Many CPUs provide fine-grained protection for Many CPUs provide fine-grained protection for memory pages, allowing the CPU to mark a page in memory pages, allowing the CPU to mark a page in memory as readable, writable, or executable.memory as readable, writable, or executable.

If the program keeps its code and data completely If the program keeps its code and data completely separate, it's possible to prevent shellcode from separate, it's possible to prevent shellcode from running by marking data pages as nonexecutable.running by marking data pages as nonexecutable.

By enforcing nonexecutable protections, the CPU By enforcing nonexecutable protections, the CPU prevents the most popular exploitation method, which prevents the most popular exploitation method, which is to transfer control flow for a location in memory is to transfer control flow for a location in memory where attacker-created data already resides.where attacker-created data already resides.

Page 17: Program Security Part 2

1717

Nonexecutable Stack And Heap ProtectionNonexecutable Stack And Heap Protection

Intel CPUs didn't enforce nonexecutable Intel CPUs didn't enforce nonexecutable memory pages until 2004.memory pages until 2004.

Some interesting workarounds were developed Some interesting workarounds were developed to overcome this limitation by other companies.to overcome this limitation by other companies.

One of the most notable ones was by the PaX One of the most notable ones was by the PaX Development team.Development team.

See documentation at http://pax.grsecurity.net/See documentation at http://pax.grsecurity.net/

Page 18: Program Security Part 2

1818

Limitations of Nonexecutable Stack And Limitations of Nonexecutable Stack And Heap ProtectionHeap Protection

Because nonexecutable memory is enforced by the Because nonexecutable memory is enforced by the CPU, by bypassing this protection directly isn't CPU, by bypassing this protection directly isn't feasible - generally, the attacker is completely feasible - generally, the attacker is completely incapacitated from directing execution to a location on incapacitated from directing execution to a location on the stack or the heap.the stack or the heap.

However, this does not prevent attackers from However, this does not prevent attackers from returning to useful code in the executable code returning to useful code in the executable code sections, whether it's in the application being exploited sections, whether it's in the application being exploited or a shared library.or a shared library.

One popular technique to circumvent these One popular technique to circumvent these protections is to have a series of return addresses protections is to have a series of return addresses constructed on the stack so that the attacker can constructed on the stack so that the attacker can make multiple calls to useful API functions.make multiple calls to useful API functions.

Page 19: Program Security Part 2

1919

Limitations of Nonexecutable Stack And Limitations of Nonexecutable Stack And Heap ProtectionHeap Protection

Often, attackers can return to an API function for Often, attackers can return to an API function for unprotecting a region of memory with data they unprotecting a region of memory with data they control.control.

This marks the target page as executable and disables This marks the target page as executable and disables the protection, allowing the exploit to run its own the protection, allowing the exploit to run its own shellcode.shellcode.

In general, this protection mechanism makes In general, this protection mechanism makes exploiting protected systems more difficult, but exploiting protected systems more difficult, but sophisticated attackers can usually find a way around sophisticated attackers can usually find a way around it.it.

With a little creativity, the existing code can be spliced, With a little creativity, the existing code can be spliced, diced, and coerced into serving the attacker's purpose.diced, and coerced into serving the attacker's purpose.

Page 20: Program Security Part 2

2020

Address Space Layout Randomization Address Space Layout Randomization (ASLR)(ASLR)

ASLR ASLR is a technology that attempts to mitigate the threat is a technology that attempts to mitigate the threat of buffer overflows by randomizing where application data of buffer overflows by randomizing where application data and code is mapped at runtime.and code is mapped at runtime.

Essentially, data and code sections are mapped to a Essentially, data and code sections are mapped to a somewhat random memory location where they are somewhat random memory location where they are loaded.loaded.

Because a critical part of buffer overflow exploitation Because a critical part of buffer overflow exploitation involves overwriting key data structures or returning to involves overwriting key data structures or returning to specific places in memory, ASLR should, in theory, specific places in memory, ASLR should, in theory, prevent reliable exploitation because attackers can no prevent reliable exploitation because attackers can no longer rely on static addresses.longer rely on static addresses.

Page 21: Program Security Part 2

2121

Limitations of ASLRLimitations of ASLR Although ASLR is a form of security by Although ASLR is a form of security by

obscurity, it's a highly effective technique for obscurity, it's a highly effective technique for preventing exploitation, especially when used preventing exploitation, especially when used with some of the other preventive technologies with some of the other preventive technologies already discussed.already discussed.

However, ASLR can still be defeated.However, ASLR can still be defeated. Defeating ASLR especially relies on finding a Defeating ASLR especially relies on finding a

weak point in the ASLR implementation.weak point in the ASLR implementation. Attackers usually attempt to adopt one of the Attackers usually attempt to adopt one of the

following approaches:following approaches:

Page 22: Program Security Part 2

2222

Limitations of ASLR - Attack ApproachesLimitations of ASLR - Attack Approaches

Find something in memory that's in a static location Find something in memory that's in a static location despite the ASLR. No matter what the static element despite the ASLR. No matter what the static element is, it's probably useful in one way or another.is, it's probably useful in one way or another. Examples of statically located elements might includeExamples of statically located elements might include

Base executables that don't contain relocation information Base executables that don't contain relocation information so the loader might not be able to relocate it.so the loader might not be able to relocate it.

Specialized data structures present in all mapped Specialized data structures present in all mapped processes such as the Windows PEB or the Linux processes such as the Windows PEB or the Linux vsyscall page.vsyscall page.

The loader itselfThe loader itself Nonrelocatable shared librariesNonrelocatable shared libraries

If ASLR fails to randomize any specific part of the process, it If ASLR fails to randomize any specific part of the process, it can be relied on and potentially able to undermine the ASLR can be relied on and potentially able to undermine the ASLR protection.protection.

Page 23: Program Security Part 2

2323

Brute force where possible.Brute force where possible. In a lot of cases, data elements are shifted in memory, but In a lot of cases, data elements are shifted in memory, but

not by a large amount.not by a large amount. An example is the current Linux executable ASLR maps An example is the current Linux executable ASLR maps

the stack at a random locationthe stack at a random location However, closer inspection on the code shows these However, closer inspection on the code shows these

mapping include only 256 possible locations.mapping include only 256 possible locations. This small set of possible locations doesn't provide for a This small set of possible locations doesn't provide for a

large randomness factor and most ASLR implementations large randomness factor and most ASLR implementations don't randomize a child process' memory layout.don't randomize a child process' memory layout.

Thus, an attacker can send requests for each possible Thus, an attacker can send requests for each possible offset and eventually achieve successful exploitation offset and eventually achieve successful exploitation when the correct offset is found.when the correct offset is found.

Limitations of ASLR - Attack ApproachesLimitations of ASLR - Attack Approaches

Page 24: Program Security Part 2

2424

SafeSEHSafeSEH

Modern Windows systems (XP SP2+, Windows 2003, Modern Windows systems (XP SP2+, Windows 2003, Vista) implement protection mechanism for the SEH Vista) implement protection mechanism for the SEH structures located on the stack.structures located on the stack.

When an exception is triggered, the exception handler When an exception is triggered, the exception handler targets addresses are examined before they are called targets addresses are examined before they are called to ensure that each is a valid exception handler to ensure that each is a valid exception handler routine.routine.

At this time, the following procedure determines an At this time, the following procedure determines an exception handler's validity:exception handler's validity:1. Get the exception handler's address, and determine which 1. Get the exception handler's address, and determine which

module (DLL or executable) the handler address is pointing module (DLL or executable) the handler address is pointing into.into.

Page 25: Program Security Part 2

2525

SafeSEHSafeSEH2. Check if there is an exception table registered.2. Check if there is an exception table registered. An exception table is a table of valid exception handlers that can An exception table is a table of valid exception handlers that can

legitimately be entered in an _EXCEPTION_REGISTRATION structure.legitimately be entered in an _EXCEPTION_REGISTRATION structure. This table is optional and modules might omit it.This table is optional and modules might omit it. In this case, the handler is assumed to be valid and can be called.In this case, the handler is assumed to be valid and can be called.

3. If the exception table exists and the handler address in the 3. If the exception table exists and the handler address in the _EXCEPTION_REGISTRATION structure doesn't match a valid _EXCEPTION_REGISTRATION structure doesn't match a valid handler entry, the structure is deemed corrupt and the handler isn't handler entry, the structure is deemed corrupt and the handler isn't called.called.

SafeSEH protection is a good complement to the stack cookies SafeSEH protection is a good complement to the stack cookies used in recent Windows releases, in that it prevents attackers used in recent Windows releases, in that it prevents attackers from using SEH overwrites as a method for bypassing the stack from using SEH overwrites as a method for bypassing the stack cookie protection.cookie protection.

Page 26: Program Security Part 2

2626

Limitations of SafeSEHLimitations of SafeSEH

However, as with other protection mechanisms, it has However, as with other protection mechanisms, it has had weaknesses in the past.had weaknesses in the past.

David Litchfield of Next Generation Security Software David Litchfield of Next Generation Security Software (NGSSoftware) wrote a paper detailing some (NGSSoftware) wrote a paper detailing some problems with early implementations of SafeSEH that problems with early implementations of SafeSEH that have since been addressed.have since been addressed.

Primary methods for bypassing SafeSEH include Primary methods for bypassing SafeSEH include returning to a location in memory that doesn't belong returning to a location in memory that doesn't belong to any module (such a PEB), returning into modules to any module (such a PEB), returning into modules without an registered exception table, or abusing without an registered exception table, or abusing defined exception handlers that might allow indirect defined exception handlers that might allow indirect running of arbitrary code.running of arbitrary code.

Page 27: Program Security Part 2

2727

Function Pointer ObfuscationFunction Pointer Obfuscation

Long-lived function pointers are often the target Long-lived function pointers are often the target of memory corruption exploits because they of memory corruption exploits because they provide a direct method for seizing control of provide a direct method for seizing control of program execution.program execution.

One method of preventing this attack is to One method of preventing this attack is to obfuscate any sensitive pointers stored in obfuscate any sensitive pointers stored in globally visible data structures.globally visible data structures.

This protection mechanism doesn't prevent This protection mechanism doesn't prevent memory corruption, but it does reduce the memory corruption, but it does reduce the probability of a successful exploit for any attack probability of a successful exploit for any attack other than a denial of service.other than a denial of service.

Page 28: Program Security Part 2

2828

Function Pointer ObfuscationFunction Pointer Obfuscation We saw earlier that an attacker might be able to We saw earlier that an attacker might be able to

leverage function pointers in the PEB of a running leverage function pointers in the PEB of a running Windows process.Windows process.

To help mitigate this attack, Microsoft is now using the To help mitigate this attack, Microsoft is now using the EncodePointer, DecodePointer, EncodePointer, DecodePointer, EncodeSystemPointer, EncodeSystemPointer, and and DecodeSystemPointer DecodeSystemPointer functions to obfuscate functions to obfuscate many of these values.many of these values.

These functions obfuscate a pointer by combining its These functions obfuscate a pointer by combining its pointer value with a secret cookie value using an XOR pointer value with a secret cookie value using an XOR exceptionexception

Recent versions of Windows also use this anti-Recent versions of Windows also use this anti-exploitation technique in parts of the heap exploitation technique in parts of the heap implementation.implementation.

Page 29: Program Security Part 2

2929

Limitations of Function Pointer ObfuscationLimitations of Function Pointer Obfuscation

This technology certainly raises the bar for exploit This technology certainly raises the bar for exploit developers, especially when combined with other developers, especially when combined with other technologies, such as ASLR and nonexecutable memory technologies, such as ASLR and nonexecutable memory pages.pages.

However, it is not a complete solution in itself and has only However, it is not a complete solution in itself and has only limited use.limited use.

Attackers can still overwrite application-specific function Attackers can still overwrite application-specific function pointers, as compilers currently don't encode function pointers, as compilers currently don't encode function pointers the application uses.pointers the application uses.

An attacker might also be able to overwrite normal An attacker might also be able to overwrite normal unencoded variables that eventually provide execution unencoded variables that eventually provide execution control through a less direct vector.control through a less direct vector.

Page 30: Program Security Part 2

3030

Limitations of Function Pointer ObfuscationLimitations of Function Pointer Obfuscation

Finally, attackers might identify circumstances Finally, attackers might identify circumstances that redirect execution control in a limited but that redirect execution control in a limited but useful way.useful way.

For example, when user-controlled data is in For example, when user-controlled data is in close proximity to a function pointer, just close proximity to a function pointer, just corrupting the low byte of an encoded function corrupting the low byte of an encoded function pointer might give attackers a reasonable pointer might give attackers a reasonable chance of running arbitrary code,chance of running arbitrary code,

This is especially true when they can make This is especially true when they can make repeated exploit attempts until a successful repeated exploit attempts until a successful value is identified.value is identified.

Page 31: Program Security Part 2

3131

Preventing Buffer Overflow Attacks Main problem:

strcpy(), strcat(), sprintf() have no range checking. “Safe” versions strncpy(), strncat() are misleading strncpy() may leave buffer unterminated. strncpy(), strncat() encourage off by 1 bugs.

Defenses: Type safe languages (Java, ML). Legacy code? Mark stack as non-executable or random stack location. Static source code analysis. Run time checking: StackGuard, Libsafe, SafeC,

(Purify).

Page 32: Program Security Part 2

3232

Finding Buffer Overflows

To find buffer overflows on a local machineTo find buffer overflows on a local machine Run web server on local machineRun web server on local machine Issue requests with long tagsIssue requests with long tags

Say, make all long tags end with “$$$$Say, make all long tags end with “$$$$$”$”

If web server crashes,If web server crashes,search core dump for “$$$$$” to find ansearch core dump for “$$$$$” to find anoverflow locationoverflow location

Some automated tools exist to find buffer Some automated tools exist to find buffer overflowsoverflows

Page 33: Program Security Part 2

3333

Finding Buffer Overflows

eEye Retina identifies known and zero day eEye Retina identifies known and zero day vulnerabilities plus provides security risk vulnerabilities plus provides security risk assessment, enabling security best practices, assessment, enabling security best practices, policy enforcement, and regulatory audits.policy enforcement, and regulatory audits.

Then use disassemblers and debuggers (e.g. Then use disassemblers and debuggers (e.g. IDA-Pro) to construct exploit IDA-Pro) to construct exploit

See http://www.hex-rays.com/idapro/ida-See http://www.hex-rays.com/idapro/ida-executive.pdfexecutive.pdf

Page 34: Program Security Part 2

3434

Finding Overflows Obtain local copy of target software. (e.g. web

server) Run on long, distinctive inputs, until program dumps

core. Search core dump for inputs to find overflow

location. Many other approaches:

Google "finding buffer overflows" (obviously!) In Safari, search on "buffer overflow attack" - get

422 hits BugTraq: See next slide

Page 35: Program Security Part 2

3535

BugTraqBugTraq

BugTraq is an electronic mailing list dedicated to issues about computer security.

On-topic issues are new discussions about vulnerabilities, vendor security-related announcements, methods of exploitation, and how to fix them.

It is a high-volume mailing list, and almost all new vulnerabilities are discussed there.

See general articles at http://www.securityfocus.com/ See BugTraq at

http://www.securityfocus.com/archive/1

Page 36: Program Security Part 2

3636

Preventing Overflows

Buffer overflows happen because C, C++, and some other languages lack array bound checking.

So don’t use C, C++, or the other languages! Stuck with them? What can be done? Use

A non-executable stack Randomization Source code analysis Run-time checking

Page 37: Program Security Part 2

3737

Nonexecutable Stack Overflows

The “famous” stack-smashing attack puts code on the stack, so this fails if the stack is not executable.

If goal is, e.g., to get a shell, no particular reason

we need to call our own code. Instead:

After the return from func(str) call exec(“/bin/sh”)

Page 38: Program Security Part 2

3838

Randomization

Address space randomization: change locations

of the stack, heap, data segment, shared libs… Both make exploits harder, but see:

www.stanford.edu/~blp/papers/asrandom.pdf

www.usenix.org/events/sec05/tech/full_papers/sovarel/sovarel.pdf

Instruction set randomization: changes opcodes

on machine. Supported by some processors! Then injected code usually won’t run… return-to-libc has to find it first…

Page 39: Program Security Part 2

3939

Use of Canaries

Coal Miner Approach: Take a canary into a mine and watch for the canary's health to change. When it does, get out fast!

A similar approach will work to prevent a stack from being corrupted.

In each stack frame, put a "canary" - something that can be located easily.

Before using the frame, check for the canary and exit gracefully if it is found.

Page 40: Program Security Part 2

4040

Stack CookiesStack Cookies Stack cookiesStack cookies, also known as , also known as canary valuescanary values, are , are

a method devised to detect and prevent a method devised to detect and prevent exploitation of a buffer overflow on the stack,exploitation of a buffer overflow on the stack,

Stack cookies are a complete solution present in Stack cookies are a complete solution present in recent default applications and libraries shipped recent default applications and libraries shipped with Windows XP SP2 (Service Pack 2) and with Windows XP SP2 (Service Pack 2) and later.later.

There are also several UNIX implementations of There are also several UNIX implementations of stack cookie protections, most notably ProPolice stack cookie protections, most notably ProPolice and Stackguard.and Stackguard.

Page 41: Program Security Part 2

4141

Stack CookiesStack Cookies Stack cookies work by inserting a random 32-bit Stack cookies work by inserting a random 32-bit

value (usually generated at runtime) on the value (usually generated at runtime) on the stack immediately after the saved return address stack immediately after the saved return address and saved frame pointer, but before the local and saved frame pointer, but before the local variables in each stack frame as shown here:variables in each stack frame as shown here:

BufferBuffer

Random value stack cookieRandom value stack cookie

Saved EBPSaved EBP

Saved EIPSaved EIP

Argument 1Argument 1

Argument 2Argument 2

BufferBuffer

Saved EBPSaved EBP

Saved EIPSaved EIP

Argument 1Argument 1

Argument 2Argument 2

Ordinary function stack frame protected function stack frame

Page 42: Program Security Part 2

4242

Stack CookiesStack Cookies

The cookie is inserted when the function is The cookie is inserted when the function is entered and is checked immediately before the entered and is checked immediately before the function returns.function returns.

If the cookie value has been altered, the If the cookie value has been altered, the program can infer that the stack has been program can infer that the stack has been corrupted and take appropriate action.corrupted and take appropriate action.

This response prevents traditional stack This response prevents traditional stack overflows from being exploitable, as the overflows from being exploitable, as the corrupted return address is never used.corrupted return address is never used.

Page 43: Program Security Part 2

4343

Limitations Of Stack CookiesLimitations Of Stack Cookies Stack cookies are effective, but not foolproof.Stack cookies are effective, but not foolproof. It prevents overwriting the saved frame pointer It prevents overwriting the saved frame pointer

and saved return address.and saved return address. But. it doesn't protect against overwriting But. it doesn't protect against overwriting

adjacent local variables.adjacent local variables. We saw earlier how overwriting local variables We saw earlier how overwriting local variables

can subvert system security, especially when can subvert system security, especially when pointer values are corrupted which the function pointer values are corrupted which the function users to modify data.users to modify data.

Modification of these pointer values usually Modification of these pointer values usually results in the attacker seizing control of the results in the attacker seizing control of the application by overwriting a function pointer or application by overwriting a function pointer or other useful values.other useful values.

Page 44: Program Security Part 2

4444

Limitations Of Stack CookiesLimitations Of Stack Cookies One way to prevent local variable corruption, is to reorder One way to prevent local variable corruption, is to reorder

local variables as this can minimize the risk of adjacent local variables as this can minimize the risk of adjacent variable overwriting.variable overwriting.

Many current stack protection systems do this.Many current stack protection systems do this. Another attack is to write past the stack cookie and Another attack is to write past the stack cookie and

overwrite the parameters to the current function.overwrite the parameters to the current function. The attacker corrupts the stack cookie by overwriting The attacker corrupts the stack cookie by overwriting

function parameters, but the goal of the attack is to not let function parameters, but the goal of the attack is to not let the function return.the function return.

In certain cases, overwriting function parameters allows the In certain cases, overwriting function parameters allows the attacker to gain control of the application before the function attacker to gain control of the application before the function returns, thus circumventing the stack cookie protection.returns, thus circumventing the stack cookie protection.

Page 45: Program Security Part 2

4545

Examples of Canaries Random canary:

Choose random string at program startup. Insert canary string into every stack frame. Verify canary before returning from function. To corrupt random canary, attacker must learn

current random string. Terminator canary:

Canary = 0, newline, linefeed, EOF String functions will not copy beyond terminator. Hence, attacker cannot use string functions to

corrupt stack.

Page 46: Program Security Part 2

4646

Limitations Of Stack CookiesLimitations Of Stack Cookies Although this technique seems as though it would be Although this technique seems as though it would be

useful to attackers, optimization can sometimes useful to attackers, optimization can sometimes inadvertently eliminate the chance of a bug being inadvertently eliminate the chance of a bug being exploited.exploited.

When a variable value is used frequently, the When a variable value is used frequently, the compiler usually generates code that reads it off the compiler usually generates code that reads it off the stack once and then keeps it in a register for the stack once and then keeps it in a register for the duration of the function or the part of the function in duration of the function or the part of the function in which the value is used repeatedly.which the value is used repeatedly.

So, even though an argument or local variable might So, even though an argument or local variable might be accessed frequently after an overflow is triggered, be accessed frequently after an overflow is triggered, attackers might not be able to use that argument to attackers might not be able to use that argument to perform arbitrary overwrites.perform arbitrary overwrites.

Page 47: Program Security Part 2

4747

Limitations Of Stack CookiesLimitations Of Stack Cookies Another similar technique on Windows is to not Another similar technique on Windows is to not

worry about the saved return address and worry about the saved return address and instead shoot for the SEH overwrite.instead shoot for the SEH overwrite.

This way, the attacker can corrupt SEH records This way, the attacker can corrupt SEH records and trigger an access violation before the and trigger an access violation before the currently running function returns.currently running function returns.

There, attacker-controlled code runs and the There, attacker-controlled code runs and the overflow is never detected.overflow is never detected.

Finally, note that stack cookies are a compile-Finally, note that stack cookies are a compile-time solution and might not be a realistic option time solution and might not be a realistic option if developers can't recompile the whole if developers can't recompile the whole application.application.

Page 48: Program Security Part 2

4848

Limitations Of Stack CookiesLimitations Of Stack Cookies

The developers might not have access to all the The developers might not have access to all the source code, such as code in commercial source code, such as code in commercial libraries.libraries.

There might also be issues with making changes There might also be issues with making changes to the build environment for a large application, to the build environment for a large application, especially with hand-optimized components.especially with hand-optimized components.

What other protection mechanisms exist?What other protection mechanisms exist?

Page 49: Program Security Part 2

4949

Stackguard

GCC patch, use random canaries Program must be recompiled. Minimal performance effects: 8% for Apache. Newer version: PointGuard.

Protects function pointers and setjmp buffers by placing canaries next to them.

More noticeable performance effects. Note: Canaries don’t offer foolproof protection.

Some stack smashing attacks can leave canaries untouched.

Page 50: Program Security Part 2

5050

StackGuard Variants - ProPoliceStackGuard Variants - ProPolice

ProPolice (IBM) - gcc 3.4.1. (ProPolice (IBM) - gcc 3.4.1. (-fstack-protector-fstack-protector)) Rearrange stack layout to prevent ptr overflow.Rearrange stack layout to prevent ptr overflow.

args

ret addr

SFP

CANARY

arrays

local variables

StackGrowth

No arrays or pointers

Ptrs, but no arrays

StringGrowth

Page 51: Program Security Part 2

5151

MS Visual Studio /GS MS Visual Studio /GS [2003][2003]

Compiler /GS option:Compiler /GS option: Combination of ProPolice and Random canary.Combination of ProPolice and Random canary. Triggers UnHandledException in case of Triggers UnHandledException in case of

Canary mismatch to shutdown process.Canary mismatch to shutdown process.

Litchfield vulnerability reportLitchfield vulnerability report Overflow overwrites exception handlerOverflow overwrites exception handler Redirects exception to attack codeRedirects exception to attack code

Page 52: Program Security Part 2

5252

Run Time Checking: LibsafeRun Time Checking: Libsafe

Libsafe (Avaya Labs)Libsafe (Avaya Labs) Dynamically loaded library.Dynamically loaded library. Intercepts calls to strcpy (dest, src)Intercepts calls to strcpy (dest, src)

Validates sufficient space in current stack Validates sufficient space in current stack

frame: frame: |frame-pointer – dest| > strlen(src)|frame-pointer – dest| > strlen(src)

If so, does strcpy, If so, does strcpy,

otherwise, terminates applicationotherwise, terminates application

destret-addrsfptopof

stacksrc buf ret-addrsfp

libsafe main

Page 53: Program Security Part 2

5353

More Methods …More Methods …

StackShieldStackShield

At function prologue, copy return address RET At function prologue, copy return address RET and SFP to “safe” location (beginning of data and SFP to “safe” location (beginning of data segment)segment)

Upon return, check that RET and SFP is equal to Upon return, check that RET and SFP is equal to copy.copy.

Implemented as assembler file processor (GCC)Implemented as assembler file processor (GCC)

Page 54: Program Security Part 2

5454

Source Code Analysis

It is undecidable to determine, from code, whether a program has a buffer overflow.

Some “rules of thumb” let us look for places where overflows are possible:

“Trust inconsistencies” – assign trust values to uses,

buffers. Look for mismatches. Look for common bugs – off by one, “bad” library calls,

memory leaks, etc… Constraint violations: propagate bounds and look for

possible out-of-bounds accesses. See: www.coverity.com/

Page 55: Program Security Part 2

5555

Run Time Checking

Check that library calls are safe at runtime. e.g. Libsafe: Intercepts calls to e.g. strcpy (dest, src)

Check for space in current stack frame: Is |frame-pointer – dest| > strlen(src)? If so, proceed.

Otherwise, terminate application. See the article:

http://www.securityfocus.com/infocus/1412

Page 56: Program Security Part 2

5656

Protecting the Stack Basic stack exploit can be prevented by marking the

stack segment as non-executable or randomizing stack location. Openwall code patches exist for Linux to allow this (Solar

Designer) Made obsolete by hardware support in Intel (XD bit) and AMD

(NX bit) processors

Problems: Does not block more general overflow exploits:

Overflow on heap: overflow buffer next to func pointer. Return into libc attack

Some applications need an executable stack

Use interpreted languages such as Java, but slow

Page 57: Program Security Part 2

5757

Stack Smashing PreventionStack Smashing Prevention

1st choice: employ non-executable stack

Set “No execute” NX bit (if available) Seems like the logical thing to do, but some

real code executes on the stack! (Java does this)

2nd choice: use safe languages (Java, C#)

3rd choice: use safer C functions For unsafe functions, there are safer versions

Page 58: Program Security Part 2

5858

Unsafe C FunctionsUnsafe C Functions

strcpy() strcat() sprintf() scanf() sscanf() fscanf() vfscanf() vsprintf() vscanf() vssanf() streadd() strecpy() strtrns() gets()

Page 59: Program Security Part 2

5959

Preventing Format-string Bugs Correct usage, input validation, snprintf

www.usenix.org/events/sec01/cowanbarringer.html

FormatGuard: count arguments to printf, parameters in format string.

Tainting: reject format strings from “untrusted” sources, strings with %n, etc…

Whitelisting: allow writes only to program addressable locations.

www.cs.washington.edu/homes/miker/format_string.pdf

Page 60: Program Security Part 2

6060

Strategies for Preventing MitigationStrategies for Preventing Mitigation

Closing the race windowClosing the race window Eliminate RW whenever possibleEliminate RW whenever possible

Techniques - many studied in operating systems Techniques - many studied in operating systems coursescourses Mutual exclusionMutual exclusion Thread safe functionsThread safe functions Use of atomic operationsUse of atomic operations Checking file properties safelyChecking file properties safely Use file descriptors not filenamesUse file descriptors not filenames Shared directoriesShared directories Temporary filesTemporary files

Page 61: Program Security Part 2

6161

Trying to Prevent Incomplete Mediation Trying to Prevent Incomplete Mediation

Unchecked data are a serious vulnerability!Unchecked data are a serious vulnerability! Possible solution: aPossible solution: anticipate problemsnticipate problems

Don’t let client return a sensitive result (like Don’t let client return a sensitive result (like totaltotal) ) that can be easily recomputed by serverthat can be easily recomputed by server

Use dUse drop-down boxrop-down boxes / choice lists for data inputes / choice lists for data input Prevent user from editing input directlyPrevent user from editing input directly

CheckCheck validity of data validity of data valuesvalues received from client received from client

Page 62: Program Security Part 2

6262

Race Detection ToolsRace Detection Tools Static analysisStatic analysis

Parses software to identify race conditionsParses software to identify race conditions Warlock for C (need annotation)Warlock for C (need annotation) ITS4 uses (database of vulnerabilities)ITS4 uses (database of vulnerabilities) RacerX for control-flow sensitive interprocedural RacerX for control-flow sensitive interprocedural

analysisanalysis Flawfinder and RATS – best public domainFlawfinder and RATS – best public domain

Extended static checkingExtended static checking Use theorem proving technologyUse theorem proving technology

Race condition detection is NP completeRace condition detection is NP complete Hence approximate detectionHence approximate detection C/C++ are difficult to analyze statically – C/C++ are difficult to analyze statically –

pointers and pointer arithmeticpointers and pointer arithmeticDynamic dispatch and templates in C++Dynamic dispatch and templates in C++

Page 63: Program Security Part 2

6363

Why Do Programmers Keep Making The Why Do Programmers Keep Making The Same Mistake?Same Mistake?

C/C++ inherently unsafe.C/C++ inherently unsafe. There is no checking of the array bounds.There is no checking of the array bounds. There are many unsafe library functions:There are many unsafe library functions:

strcpy()strcpy() sprintf()sprintf() gets()gets() scanf() etc.scanf() etc.

C/C++ gains in performance by not checking array bounds.C/C++ gains in performance by not checking array bounds. The following languages are largely, but not totally, The following languages are largely, but not totally,

immune and they run slower: D, Java, Python, Rubyimmune and they run slower: D, Java, Python, Ruby

Page 64: Program Security Part 2

6464

Some Unsafe libc Functions

strcpy (char *dest, const char *src) strcat (char *dest, const char *src) gets (char *s) scanf ( const char *format, … ) printf (conts char *format, … ) and others

Page 65: Program Security Part 2

6565

Even Supposedly Safe Languages May Even Supposedly Safe Languages May Have ProblemsHave Problems

Many library routines as well as routines that call Many library routines as well as routines that call them are often written in C and C++.them are often written in C and C++.

Interactions between the application and these Interactions between the application and these routines may leave open the possibility of a routines may leave open the possibility of a buffer overflow.buffer overflow.

Attacks are possible any time software accepts Attacks are possible any time software accepts alphanumeric input from a user, whether through alphanumeric input from a user, whether through the GUI, via the command prompt, or by using the GUI, via the command prompt, or by using APIs (application programmer interfaces).APIs (application programmer interfaces).

Page 66: Program Security Part 2

6666

Guiding Principles for Software SecurityGuiding Principles for Software Security

1.1. Secure the weakest link.Secure the weakest link.

2.2. Practice defense in depth.Practice defense in depth.

3.3. Fail securely.Fail securely.

4.4. Follow the principle of least privilege.Follow the principle of least privilege.

5.5. Compartimentalize.Compartimentalize.

6.6. Keep it simple.Keep it simple.

7.7. Promote privacy.Promote privacy.

8.8. Remember that hiding secrets is hard.Remember that hiding secrets is hard.

9.9. Be reluctant to trust.Be reluctant to trust.

10.10.Use your resources.Use your resources.

Page 67: Program Security Part 2

6767

More Questions to Ask - They Do Not EndMore Questions to Ask - They Do Not End• Your program crashes. What does the operating system

do in that event? Does this action put the security of your program, or worse, that of your computer at risk? What can you do to ensure that things won’t go away?

• When your program runs and creates new files, how will access permissions be set? Do you want to explicitly control that, or should you just not worry and be “happy”?

You need to create a temporary file that will contain You need to create a temporary file that will contain sensitive data. In what directory should you store it? sensitive data. In what directory should you store it? What name do you give to it? What name do you give to it? Do you want to leave this file around if your program crashes?

Page 68: Program Security Part 2

6868

More Questions to Ask - They Do Not EndMore Questions to Ask - They Do Not End If data comes into your application, is there a If data comes into your application, is there a

potential for a malicious user to feed it input that potential for a malicious user to feed it input that makes the program crash or “makes the program crash or “misbehavemisbehave”.”.

The user gives you a filename or a path. How do The user gives you a filename or a path. How do you resolve this name to the actual file that it you resolve this name to the actual file that it refers to in the filesystem?refers to in the filesystem?

If your application takes an email address as If your application takes an email address as input, do you always verify that this is a proper, input, do you always verify that this is a proper, valid address?valid address?

If you’re programming in a language that supports If you’re programming in a language that supports exceptions, do you use and handle exceptions? exceptions, do you use and handle exceptions?

Page 69: Program Security Part 2

6969

More Questions to Ask - They Do Not EndMore Questions to Ask - They Do Not End

You have a file with encrypted information. In You have a file with encrypted information. In order for your program to use, you need to decrypt order for your program to use, you need to decrypt it first. You don’t want to store the decrypted data it first. You don’t want to store the decrypted data in disk, so you put it in a memory buffer. Is this a in disk, so you put it in a memory buffer. Is this a hazard?hazard?

When you’re done with a buffer and you delete it or free it, are you sure you’re not spilling sensitive information? Understand how memory management works. The security of your program will depend on how you use dynamic memory allocation primitives.

Page 70: Program Security Part 2

7070

More Questions to Ask - They Do Not EndMore Questions to Ask - They Do Not End

You have a file with sensitive information. You You have a file with sensitive information. You simply erase it with simply erase it with rmrm. Are your secrets still . Are your secrets still safe?safe? The file can be undeleted. The disk blocks will still

contain your data. Overwriting each individual block once will not solve the problem either. You want to catch every block that was allocated to this file, and write some bogus data on it multiple times: alternate passes in which you write patterned-data and random data.

Page 71: Program Security Part 2

7171

A Few Rules Of Thumb:

Trust no one: All input is guilty until proven otherwise.

Validate both at input to application and at input to each component.

Beware of special commands, characters, and quoting.

Understand the data so you can filter it effectively.

See http://www.secureprogramming.com/

for ongoing discussions on these questions.