Software Security
Buffer
Overflows
Common Programming
Mistakes
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Poor design choices / assumptions
Failing to check user supplied input
Buffer overflows
Incorrect levels and separation of privileges
Poor default settings
Predictable sources of randomness
Race conditions
Poor failure modes
Insufficient testing
Failure to protect secrets properly
Poor design review
Poor documentation and commenting
Poor maintenance of legacy code
Bad programming languages
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).
SECURITY INNOVATION ©2003
Frequency of Buffer Overflow
Attacks
Total Number
SECURITY INNOVATION ©2003
% of Total Exploits
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
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.
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()
…
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.
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.
SECURITY INNOVATION ©2003
Continued..
char *gets(char *s);
“This is white data. Attack!!
\n”
Attack!! data \n”
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.
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
SECURITY INNOVATION ©2003
Buffer Overflows
• Overview: overwrite return address
return address
Create a string that:
buffer
shell code
…
• Contains shell code
• Overwrites return address
to point to that shell code
…
Program Stack
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
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";
SECURITY INNOVATION ©2003
Scope
•
•
•
•
•
•
•
Stack Overflows
Simple EIP Attacks
Linux
X86
Beginner
Intermediate
Advanced
SECURITY INNOVATION ©2003
Overview
•
•
•
•
•
•
Basic O/S and Memory Concepts
Stacks and Heaps
Calling Convention
C Variables & String Handling
Vector and Payload
Defeating Attacks
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
SECURITY INNOVATION ©2003
Executable Files
• Program file (PE) Windows (ELF) Linux
– Many sections
– Loaded into virtual address locations
– Basic Section Types
• Data
• Text
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
SECURITY INNOVATION ©2003
Yet More Heap
• Grows randomly
– Yes, it really does
– Considered to grow up
• Manually expanded
– Malloc()
– Brk()
SECURITY INNOVATION ©2003
Heap Continued
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)
SECURITY INNOVATION ©2003
The Stack Continued
SECURITY INNOVATION ©2003
More Stack – Get Used to It
• Grows down
• Randomly & FIFO accessed
• Instructions
– Push
– Pop
• Grows Automatically
– Guard Pages
SECURITY INNOVATION ©2003
Memory usage
• In an IBM-PC,
program code and
data (usually)
reside somewhere
in the lower 640KB
of system memory.
0
655359
SECURITY INNOVATION ©2003
Memory usage
• In an IBM-PC,
program code and
data (usually)
reside somewhere
in the lower 640KB
of system memory.
0
304359
Program
and Data
350759
655359
SECURITY INNOVATION ©2003
Memory usage
• Let’s examine the
management of the
data areas within
the region assigned
to the program.
0
304359
Program
and Data
350759
655359
SECURITY INNOVATION ©2003
Memory usage
• The data area is
composed of two
regions.
304359
Instructions
350759
SECURITY INNOVATION ©2003
Memory usage
• The data area is
composed of two
regions.
• One is called the
heap.
304359
Instructions
Heap
350759
SECURITY INNOVATION ©2003
Memory usage
• The data area is
composed of two
regions.
• One is called the
heap.
• The other is called
the stack.
304359
Instructions
Heap
Stack
350759
SECURITY INNOVATION ©2003
Memory usage
• The heap contains
things like static
and external
variables.
304359
Instructions
Heap
Stack
350759
SECURITY INNOVATION ©2003
Memory usage
• The stack contains
things like
automatic
variables and
function arguments.
304359
Instructions
Heap
Stack
350759
SECURITY INNOVATION ©2003
Memory usage
• As the program
runs, the stack
grows and shrinks
towards the lower
addresses.
304359
Instructions
Heap
Stack
350759
SECURITY INNOVATION ©2003
Memory usage
• For example, when
a function is called,
the stack grows.
304359
Instructions
Heap
Stack
350759
SECURITY INNOVATION ©2003
Memory usage
• For example, when
a function returns to
the calling program,
the stack shrinks.
304359
Instructions
Heap
Stack
350759
SECURITY INNOVATION ©2003
Memory usage
• As the program
runs, the heap
grows and shrinks
towards the higher
addresses.
304359
Instructions
Heap
Stack
350759
SECURITY INNOVATION ©2003
Memory usage
• C++ allows you to
allocate and free
memory assigned to
the heap.
304359
Instructions
Heap
Stack
350759
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
SECURITY INNOVATION ©2003
Calling Subroutines
• Many ways to jump from code to code
– Jmp
– Modify eip
• What about returning?
SECURITY INNOVATION ©2003
Calling Subroutines Again
• Two instructions
– Call
• Push eip onto stack
• Jump to specified address
– Ret
• Pop eip from stack
• Continue execution
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
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
SECURITY INNOVATION ©2003
Stack Overflow Concept
• Saved eip is vulnerable
• Overwrite
– Jump to arbitrary location on return
SECURITY INNOVATION ©2003
Variables
• Automatic variables go onto stack
• In C:
– Local variables
– Auto keyword (storage class declaration)
– Vmalloc()
SECURITY INNOVATION ©2003
C Example
int example(int a, int b) {
int temp;
temp = a + b;
return(temp);
}
SECURITY INNOVATION ©2003
C Strings
• Null terminate character arrays
• Example:
• No defined length, determined by null
SECURITY INNOVATION ©2003
C String Handling
• Programs allocate buffers to parse strings in
• Typically local/automatic variables
– Usually temporary
– Malloc() is too much effort
SECURITY INNOVATION ©2003
C Example Stack
SECURITY INNOVATION ©2003
Beginner
Beginner
• 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
SECURITY INNOVATION ©2003
Buffer Overflow Attacks
Process Address Space
0xFFFF
Top of Stack
Attack Code
Stack
Growth
RA
Local Variables…
buffer
buffer
buffer
0x0000
buffer
SECURITY INNOVATION ©2003
String
Growth
Example Illustrated
Process Address Space
argc
user stack
RA
sfp
long_ptr
i
buffer
large_string[128]
Shellcode[]
heap
bss
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);
}
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?
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
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)
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
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
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’
SECURITY INNOVATION ©2003
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
\x2f\x62\x69\x6e\x2f\x73\x68
jmp 0x1f
popl %esi
movl %esi,0x8(%esi)
xorl %eax,%eax
movb %eax,0x7(%esi)
movl %eax,0xc(%esi)
movb $0xb,%al
movl %esi,%ebx
leal 0x8(%esi),%ecx
leal 0xc(%esi),%edx
int $0x80
xorl %ebx,%ebx
movl %ebx,%eax
inc %eax
int $0x80
call -0x24
.string "/bin/sh"
SECURITY INNOVATION ©2003
// jump to call
// put “/bin/sh” add in esi
// put esi in esi + 8
// eax = 0
// NULL terminate string
// 4 byte NULL to esi +0xc(12)
// put 0xb(11) in al
// copy esi to ebx
// put add of esi+8 in ecx
// put add of esi+0xc(12) in edx
// interrupt 80 (execve)
// ebx = 0
// eax = 0
// eax += 1
// interrupt 80 (exit)
// call to 1st intruction after jmp
Example
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);
}
SECURITY INNOVATION ©2003
Problems
• 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?
SECURITY INNOVATION ©2003
Solutions
• We can make educated guess
• Modify payload to make remove need for
accuracy
SECURITY INNOVATION ©2003
Guessing
• 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)
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
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’;
}
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
SECURITY INNOVATION ©2003
Intermediate
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
SECURITY INNOVATION ©2003
Exploits
• 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
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
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
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
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.
SECURITY INNOVATION ©2003
Injection Vector
•
•
•
•
•
Target Dependant
OS Dependant
Application Version Dependant
Protocol Dependant
Encoding Dependant
SECURITY INNOVATION ©2003
Payload
• 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
SECURITY INNOVATION ©2003
Payload
• Denial of Service
– use as launching point (arp spoofing)
• Remote Shell (common)
– covert channel or ‘netcat’ like
• Worm/Virus
– extremely dangerous
• Rootkit (common - stealth)
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
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.
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
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
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
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
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
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.
SECURITY INNOVATION ©2003
Advanced
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.
SECURITY INNOVATION ©2003
Challenges
• 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
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
SECURITY INNOVATION ©2003
Address Housekeeping
IP
A
B
C
D
SP
BP
IP
DI
SI
FLAG
code
heap
stack
SECURITY INNOVATION ©2003
Stack Overflow
00 40 20 1C
00 40 20 14
Cant Write Past Here
00 40 20 10
Buffer Space
00 40 20 08
EIP
00 40 20 18
00 40 20 1C
SECURITY INNOVATION ©2003
The Problem with NULL
00 40 20 08
00 40 20 10
ATTACK
CODE
00 40 20 1C
00 40 20 14
EIP
00 40 20 18
00 40 20 1C
SECURITY INNOVATION ©2003
x00
STOPS
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
SECURITY INNOVATION ©2003
EIP
OK
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
SECURITY INNOVATION ©2003
We Store Address in
Housekeeping Data
00 40 21 04
00 40 21 00
Allowable
ATTACK
Buffer
Space
CODE
00 40 20 0C
0C 20
68 40
45 00
7F
00 40 20 08 CD
00 40 20 04
00 40 20 00
SECURITY INNOVATION ©2003
Original
New
Address
Address
Injection is Complete
• We control the instruction pointer
04 21 40 00
New Address
SECURITY INNOVATION ©2003
Where to put the payload
00 40 21 04
00 40 21 00
Allowable
ATTACK
Buffer
CODE
Space
00 40 20 0C
00 40 20 08
04 21EIP
40 00
00 40 20 04
00 40 20 00
SECURITY INNOVATION ©2003
New
Address
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
SECURITY INNOVATION ©2003
Using More Stack for Payload
77 40 20 08
77 40 20 0C
ATTACK
Allowable
CODE
Buffer
Space
77 40 20 10
77 40 20 14
EIP68 77
0D 45
77 40 20 18
77 40 20 1C
SECURITY INNOVATION ©2003
No NULL
in
Address
NULL
OK
Much Larger Payload
Allowable
Buffer
Space
EIPEIP
New
Available
Payload
Area
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
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
SECURITY INNOVATION ©2003
A Register Points to the Stack
A
IP
•IP
B
DI
C
SI
D
FLAG
code
SP
BP
heap
stack
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
SECURITY INNOVATION ©2003
Push a Register then Return
• Push register
– push eax = 50
– push ebx = 53
– etc
• Then RET
– RET = C3
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”
SECURITY INNOVATION ©2003
NOP Sled
Allowable
Buffer
Space
New EIP
Start of Payload
NOP
Sled
Slide up to payload
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
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
SECURITY INNOVATION ©2003
Now for the Payload
•
•
•
•
Using Loaded Functions
Encoding our own data
Loading new functions & DLL’s
Making a shell
SECURITY INNOVATION ©2003
The Payload
NOP Sled
Real Code
DATA
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
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
SECURITY INNOVATION ©2003
WORMS
• 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?
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)
SECURITY INNOVATION ©2003
Other Stack / Heap Attacks
• Heap Overflows
– Interesting area
• Format strings
SECURITY INNOVATION ©2003
Attack Summary
• Injection is not the same as payload
• Payloads can perform
–
–
–
–
Denial of Service
WORM
Remote Shell
Rootkit
SECURITY INNOVATION ©2003
Attack Summary
• Injection has many challenges
–
–
–
–
NULL characters
Stack size
Highland/Lowland address
Calling thru CPU registers
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
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
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
SECURITY INNOVATION ©2003
StackGuard
• 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.
SECURITY INNOVATION ©2003
StackGuard
1.
2.
By detecting change of
the RA before the
function returns. (more
efficient and portable).
By completely
preventing the write to
the RA (more secure).
0xffff
Top of Stack
Return Address
Canary Word
Local Variables…
buffer
0x0000
SECURITY INNOVATION ©2003
Canary Word Next to
Return Address
String Growth
Prevents changes to
active RAs in 2 ways:
Stack Growth
•
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.
SECURITY INNOVATION ©2003
StackGuard - Detecting RA Change
Before Return
• StackGuard implementation - simple patch to
gcc 2.7.2.2.
• 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.
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
SECURITY INNOVATION ©2003
MemGuard
• MemGuard: used to
protect an RA when a
function is called, &
unprotect the RA when
the function returns.
• Adaptive Defense
Strategies
push a
push b
move 164 into a
move arg[0] into b
trap 0x80
pop b
pop a
Function Prologue Code:
Protecting the Return
Address With
MemGuard
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.
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.
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.
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.
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
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.
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
SECURITY INNOVATION ©2003
Defeating Openwall
• Use Global Offset Table Functions
• Works well if program maps any useful
functions
SECURITY INNOVATION ©2003
Solutions
• Programming problem
• Easy to miss
• Strcpy, sprintf, strcat etc. don’t make it any
easier
SECURITY INNOVATION ©2003
Ultimate Solution
• Bounds Checking
– Major processing impact
• Second best, remove strcpy, strcat etc from
libc
– Breaks almost every program in existence
SECURITY INNOVATION ©2003
Solutions to Buffer Overflow
Attacks
Eliminate Use of Vulnerable C functions
Function
Suitable Replacement
gets()
sprintf()
strcat()
strcpy()
streadd()
strtrns()
index()
vsprintf()
fscanf()
scanf()
getopt()
getpass()
realpath()
fgets()
strncat()
strncpy()
SECURITY INNOVATION ©2003
Conclusion
• 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
SECURITY INNOVATION ©2003
Conclusion
• 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
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.
SECURITY INNOVATION ©2003
The Java Solution
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
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.
SECURITY INNOVATION ©2003
The Java Sandbox
Local or remote code
Security Policy
• Java SandBox - provides
an environment on the
computer where the
program can play but
confined within certain
bounds.
Class Loader
sandbox
JVM
Valuable resources
No built-in
notion of
trusted code
SECURITY INNOVATION ©2003
Codes run with
different permissions
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.
SECURITY INNOVATION ©2003
Anatomy of a Java Application
Local Class Files
Remote Class Files
Signed Class Files
Bytecode Verifier
Core API Class Files
Security
Package
Key Database
Class Loader
Core Java API
Security Manager
Access Controller
Operating System
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 - www.Acme.com and
www.EvilSite.org.
SECURITY INNOVATION ©2003
Rules
• 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.
SECURITY INNOVATION ©2003
Enforcement of Rules
• Done at 3 different
times
Class
Loaded
• The Bytecode Verifier
Mini-Theorem Prover
proves:
– Class file has correct
format.
– final classes not
subclassed
SECURITY INNOVATION ©2003
Bytecode Verifier
Bytecodes
– Compile time
– Link time
– Runtime
Class
Object
Methods
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
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.
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)
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).
Network
Browser
An untrusted class cannot
directly connect to the database
server
SECURITY INNOVATION ©2003
Access Controller
• Decides whether access
to a critical system
resource should be
permitted or denied.
• Code Source.
• Permissions.
• Policies .
• Protection Domains.
SECURITY INNOVATION ©2003
Malicious Applets
• 3 classes of attacks
– Denial of service
– Invasion of privacy
– Annoyance
• Collections on the web
• Easy and common
SECURITY INNOVATION ©2003
Attack Applets
• At least 15 serious security bugs
• Major news when discovered
• Result in full system penetration
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
SECURITY INNOVATION ©2003
Hostile Applets
• Examples of Hostle applets
– Ungrateful.java - 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.
– AppletKiller.java- kills any applets on your PC and any other
applets that you download.
– TripleThreat.java- Bombards your monitor with black screens
so that you don’t know what actions you are taking, while it
screams like a banshee.
– Scapegoat.java- very popular, forces you to visit the same
website over and over again opening a new window each
time.
SECURITY INNOVATION ©2003
Race Conditions
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
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
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
SECURITY INNOVATION ©2003
Simple Race Condition
Process 1
Process 2
1
X := 0 ;
X := 0 ;
2
Do something…
Do something…
3
X := X + 1 ;
X := X – 1 ;
4
Print x
Print x
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
SECURITY INNOVATION ©2003
Race Conditions
Example:
• Print 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
SECURITY INNOVATION ©2003
Race Conditions
• A race condition attack exploits the fact that multiple
instruction transactions are not atomic
Example:
• Race condition in the old UNIX “mkdir” command
– mkdir executed with two Stages:
• Storage allocated
• Ownership 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 /tmp
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??
SECURITY INNOVATION ©2003
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.
SECURITY INNOVATION ©2003
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.
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.
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.
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.
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.
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:
– RSA exponentiation
– Password checking and lengths
– Inter-keystroke timing (e.g. attack on ssh)
SECURITY INNOVATION ©2003
Timing Attacks
• 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.
SECURITY INNOVATION ©2003
Timing Attacks
• 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.
SECURITY INNOVATION ©2003
Descargar

Slide 1