SlideShare ist ein Scribd-Unternehmen logo
1 von 41
Downloaden Sie, um offline zu lesen
Course 2: Programming Issues,
Section 2
Pascal Meunier, Ph.D., M.Sc., CISSP
May 2004; updated July 30, 2004
Developed thanks to the support of Symantec Corporation,
NSF SFS Capacity Building Program (Award Number 0113725)
and the Purdue e-Enterprise Center
Copyright (2004) Purdue Research Foundation. All rights reserved.
Course 2 Learning Plan


   Buffer Overflows
   Format String Vulnerabilities
   Code Injection and Input Validation
   Cross-site Scripting Vulnerabilities
   Links and Race Conditions
   Temporary Files and Randomness
   Canonicalization and Directory Traversal
Learning objectives


   Learn that format strings are interpreted, therefore
    are similar to code
   Understand the definition of a format string
    vulnerability
   Know how they happen
   Know how to format strings safely with regular "C"
    functions
   Learn other defenses against the exploitation of
    format string vulnerabilities
Format String Issues: Outline


   Introduction to format strings
   Fundamental "C" problem
   Examples
   Definition
   Importance
   Survey of unsafe functions
   Case study: analysis of cfingerd 1.4.3 vulnerabilities
   Preventing format string vulnerabilities without
    programming
   Lab: Find and fix format string vulnerabilities
   Tools to find string format issues
What is a Format String?


   In “C”, you can print using a format string:
   printf(const char *format, ...);
   printf(“Mary has %d cats”, cats);
     – %d specifies a decimal number (from an int)
     – %s would specify a string argument,
     – %X would specify an unsigned uppercase hexadecimal
       (from an int)
     – %f expects a double and converts it into decimal notation,
       rounding as specified by a precision argument
     – etc...
Fundamental "C" Problem


   No way to count arguments passed to a "C"
    function, so missing arguments are not detected
   Format string is interpreted: it mixes code and data
   What happens if the following code is run?
   int main () {
        printf("Mary has %d cats");
    }
Result


   % ./a.out
    Mary has -1073742416 cats
   Program reads missing arguments off the stack!
      – And gets garbage (or interesting stuff if you want to probe
        the stack)
Probing the Stack


   Read values off stack
   Confidentiality violations
   printf(“%08X”)
    x (X) is unsigned hexadecimal
    0: with ‘0’ padding
    8 characters wide: ‘0XAA03BF54’
    4 bytes = pointer on stack, canary, etc...
User-specified Format String


   What happens if the following code is run,
    assuming there always is an argument input by a
    user?
   int main(int argc, char *argv[])
    {
        printf(argv[1]);
        exit(0);
    }
   Try it and input "%s%s%s%s%s%s%s%s%s"
    How many "%s" arguments do you need to crash
    it?
Result


   % ./a.out "%s%s%s%s%s%s%s"
    Bus error
   Program was terminated by OS
     – Segmentation fault, bus error, etc... because the program
       attempted to read where it wasn't supposed to
   User input is interpreted as string format (e.g., %s,
    %d, etc...)
   Anything can happen, depending on input!
   How would you correct the program?
Corrected Program


   int
    main(int argc, char *argv[])
    {
        printf(“%s”, argv[1]);
        exit(0);
    }
   % ./a.out "%s%s%s%s%s%s%s"
    %s%s%s%s%s%s%s
Format String Vulnerabilities


   Discovered relatively recently ~2000
   Limitation of “C” family languages
   Versatile
     – Can affect various memory locations
     – Can be used to create buffer overflows
     – Can be used to read the stack
   Not straightforward to exploit, but examples of root
    compromise scripts are available on the web
     – "Modify and hack from example"
Definition of a Format String Vulnerability


   A call to a function with a format string argument,
    where the format string is either:
     – Possibly under the control of an attacker
     – Not followed by the appropriate number of arguments
   As it is difficult to establish whether a data string
    could possibly be affected by an attacker, it is
    considered very bad practice to place a string to
    print as the format string argument.
     – Sometimes the bad practice is confused with the actual
       presence of a format string vulnerability
How Important Are Format String
Vulnerabilities?

   Search NVD (icat) for “format string”:
     –   115 records in 2002
     –   153 total in 2003
     –   173 total in April 2004
     –   363 in February 2006
   Various applications
     –   Databases (Oracle)
     –   Unix services (syslog, ftp,...)
     –   Linux “super” (for managing setuid functions)
     –   cfingerd CVE-2001-0609
   Arbitrary code execution is a frequent consequence
Functions Using Format Strings


     printf - prints to"stdout" stream
     fprintf - prints to stream
     warn - standard error output
     err - standard error output
     setproctitle - sets the invoking process's title
     sprintf(char *str, const char *format, ...);
      – sprintf prints to a buffer
      – What’s the problem with that?
Sprintf Double Whammy


   format string AND buffer overflow issues!
   Buffer and format string are usually on the stack
   Buffer overflow rewrites the stack using values in
    the format string
Better Functions Than sprintf


   Note that these don't prevent format string
    vulnerabilities:
     – snprintf(char *str, size_t size, const char *format, ...);
          sprintf with length check for "size"
     – asprintf(char **ret, const char *format, ...);
          sets *ret to be a pointer to a buffer sufficiently large to hold
           the formatted string (note the potential memory leak).
Custom Functions Using Format Strings


   It is possible to define custom functions taking
    arguments similar to printf.
   wu-ftpd 2.6.1 proto.h
     – void reply(int, char *fmt,...);
     – void lreply(int, char *fmt,...);
     – etc...
   Can produce the same kinds of vulnerabilities if an
    attacker can control the format string
Write Anything Anywhere


   "%n" format command
   Writes a number to the location specified by
    argument on the stack
     – Argument treated as int pointer
         Often either the buffer being written to, or the raw input, are
          somewhere on the stack
            –   Attacker controls the pointer value!
     – Writes the number of characters written so far
         Keeps counting even if buffer size limit was reached!
         “Count these characters %n”
   All the gory details you don't really need to know:
     – Newsham T (2000) "Format String Attacks"
Case Study: Cfingerd 1.4.3


   Finger replacement
    – Runs as root
    – Pscan output: (CVE-2001-0609)
        defines.h:22 SECURITY: printf call should have "%s" as
         argument 0
        main.c:245 SECURITY: syslog call should have "%s" as
         argument 1
        main.c:258 SECURITY: syslog call should have "%s" as
         argument 1
        standard.c:765 SECURITY: printf call should have "%s" as
         argument 0
        etc... (10 instances total)
    – Discovery: Megyer Laszlo, a.k.a. "Lez"
Cfingerd Analysis


   Most of these issues are not exploitable, but one is,
    indirectly at that...
   Algorithm (simplified):
     – Receive an incoming connection
         get the fingered username
     – Perform an ident check (RFC 1413) to learn and log the
       identity of the remote user
     – Copy the remote username into a buffer
     – Copy that again into "username@remote_address"
         remote_address would identify attack source
     – Answer the finger request
     – Log it
Cfingerd Vulnerabilities


   A string format vulnerability giving root access:
     – Remote data (ident_user) is used to construct the
       format string:
     – snprintf(syslog_str, sizeof(syslog_str),
           "%s fingered from %s",
           username, ident_user
       );
       syslog(LOG_NOTICE, (char *) syslog_str);
   An off-by-one string manipulation (buffer overflow)
    vulnerability that
     – prevents remote_address from being logged (useful if
       attack is unsuccessful, or just to be anonymous)
     – Allows ident_user to be larger (and contain shell code)
Cfingerd Buffer Overflow Vulnerability


   memset(uname, 0, sizeof(uname));
    for (xp=uname;
        *cp!='0' && *cp!='r' &&
    *cp!='n'
        && strlen(uname) < sizeof(uname);
        cp++
    )
       *(xp++) = *cp;
   Off-by-one string handling error
     – uname is not NUL-terminated!
     – because strlen doesn't count the NUL
   It will stop copying when strlen goes reading off
    outside the buffer
Direct Effect of Off-by-one Error


   char buf[BUFLEN], uname[64];
   "uname" and "buf" are "joined" as one string!
   So, even if only 64 characters from the input are
    copied into "uname", string manipulation functions
    will work with "uname+buf" as a single entity
   "buf" was used to read the response from the
    ident server so it is the raw input
Consequences of Off-by-one Error


  1) Remote address is not logged due to size
     restriction:
        snprintf(bleah, BUFLEN, "%s@%s", uname,
         remote_addr);
        Can keep trying various technical adjustments
         (alignments, etc...) until the attack works, anonymously
  2) There's enough space for format strings,
     alignment characters and shell code in buf (~60
     bytes for shell code):
        Rooted (root compromise) when syslog call is made
            i.e., cracker gains root privileges on the computer
             (equivalent to LocalSystem account)
Preventing Format String Vulnerabilities


  1) Always specify a format string
        Most format string vulnerabilities are solved by specifying
         "%s" as format string and not using the data string as
         format string
  2) If possible, make the format string a constant
        Extract all the variable parts as other arguments to the call
        Difficult to do with some internationalization libraries
  3) If the above two practices are not possible, use
     defenses such as FormatGuard (see next slides)
     – Rare at design time
     – Perhaps a way to keep using a legacy application and
       keep costs down
     – Increase trust that a third-party application will be safe
Windows


  Demo code for format string exploit in Howard and
   Leblanc (2nd Ed.)
    – Same mechanisms as in UNIX-type systems
    – Prevented the same way
Defenses Against Exploitation


   FormatGuard
    – Use compiler macro tricks to count arguments passed
        Special header file
    – Patch to glibc
        Printf wrapper that counts the arguments needed by format
         string and verifies against the count of arguments passed
    – Kill process if mismatch
        What’s the problem with that?
FormatGuard Limitations


   What do you do if there's a mismatch in the
    argument count?
     – Terminate it (kill)
          Not complete fix, but DoS preferable to root compromise
     – If process is an important process that gets killed, Denial-
       of-Service attacks are still possible
          Although if you only manage to kill a "child process"
           processing your own attack, there's no harm done
FormatGuard Limitations (Cont.)


   Doesn't work when program bypasses
    FormatGuard by using own printf version or library
     – wu-ftpd had its own printf
     – gftp used Glib library
     – Side note: See how custom versions of standard
       functions make retrofit solutions more difficult?
          Code duplication makes patching more difficult
           Secure programming is the most secure option
Code Scanners


   Pscan searches for format string functions called
    with the data string as format string
     – Can also look for custom functions
         Needs a helper file that can be generated automatically
            –   Pscan helper file generator at
                http://www.cerias.purdue.edu/homes/pmeunier/dir_pscan.html
     – Few false positives
   http://www.striker.ottawa.on.ca/~aland/pscan/
gcc Options


   -Wformat (man gcc)
    – "Check calls to "printf" and "scanf", etc., to make sure that
      the arguments supplied have types appropriate to the
      format string specified, and that the conversions specified
      in the format string make sense. "
    – Also checks for null format arguments for several functions
         -Wformat also implies -Wnonnull
   -Wformat-nonliteral (man gcc)
    – "If -Wformat is specified, also warn if the format string is
      not a string literal and so cannot be checked, unless the
      format function takes its format arguments as a "va_list"."
gcc Options


   -Wformat-security (man gcc)
    – "If -Wformat is specified, also warn about uses of format
      functions that represent possible security problems. At
      present, this warns about calls to "printf" and "scanf"
      functions where the format string is not a string literal and
      there are no format arguments, as in "printf (foo);". This
      may be a security hole if the format string came from
      untrusted input and contains %n. (This is currently a
      subset of what -Wformat-nonliteral warns about, but in
      future warnings may be added to -Wformat-security that
      are not included in -Wformat-nonliteral.)"
   -Wformat=2
    – Equivalent to -Wformat -Wformat-nonliteral -Wformat-
      security.
Making gcc Look for Custom Functions


   Function attributes
     – Keyword "__attribute__" followed by specification
     – For format strings, use "__attribute__ ((format))"
     – Example:
         my_printf (void *my_object,
                     const char *my_format, ...)
            __attribute__ ((format (printf, 2, 3)));
   gcc can help you find functions that might benefit
    from a format attribute:
     – Switch: "-Wmissing-format-attribute"
     – Prints "warning: function might be possible
       candidate for `printf' format attribute"
       when appropriate
Lab


  Jared wrote a server program with examples of
   format string vulnerabilities
      – Get it from the USB keyring, web site or FTP server
        (follow the instructor's directions)
  Usage
      – Compile with 'make vuln_server'
      – Run with './vuln_server 5555'
      – Open another shell window and type 'telnet localhost
        5555'
      – Find and fix all format string vulnerabilities
      – Try the gcc switches
First Lab Vulnerability


   What happens when you type in the string "Hello
    world!"? ( it's printed back in reverse)
   Type in a long string (more than 100 characters). It
    should crash. Where is the buffer overflow?
   Fix the buffer overflow, recompile, and
    demonstrate that it doesn't crash on long input
    lines any more.
   Bonus: Can you get a shell?
     – We didn't teach how to do that because our primary goal
       is to teach how to avoid the vulnerabilities, and as this lab
       demonstrates, you can do that without knowing how to
       get a shell
Second Lab Vulnerability


  1) Where is the format string problem?
  2) How do you crash the program? Hint: use %s
  3) How do you print the contents of memory to
     divulge the secret which is 0xdeadc0de? Hint: use
     %08x
  4) Bonus: Can you get a shell?
Third Lab Vulnerability


   Latent vulnerability hidden somewhere...
Questions or Comments?


  §
About These Slides


     You are free to copy, distribute, display, and perform the work; and
      to make derivative works, under the following conditions.
      –   You must give the original author and other contributors credit
      –   The work will be used for personal or non-commercial educational uses
          only, and not for commercial activities and purposes
      –   For any reuse or distribution, you must make clear to others the terms of
          use for this work
      –   Derivative works must retain and be subject to the same conditions, and
          contain a note identifying the new contributor(s) and date of modification
      –   For other uses please contact the Purdue Office of Technology
          Commercialization.

   Developed thanks to the support of Symantec
    Corporation
Pascal Meunier
pmeunier@purdue.edu
Contributors:
Jared Robinson, Alan Krassowski, Craig Ozancin, Tim
Brown, Wes Higaki, Melissa Dark, Chris Clifton, Gustavo
Rodriguez-Rivera

Weitere ähnliche Inhalte

Was ist angesagt?

Yandex may 2013 a san-tsan_msan
Yandex may 2013   a san-tsan_msanYandex may 2013   a san-tsan_msan
Yandex may 2013 a san-tsan_msanYandex
 
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itEvgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itSergey Platonov
 
Rust LDN 24 7 19 Oxidising the Command Line
Rust LDN 24 7 19 Oxidising the Command LineRust LDN 24 7 19 Oxidising the Command Line
Rust LDN 24 7 19 Oxidising the Command LineMatt Provost
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects 100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects Andrey Karpov
 
Mathematicians: Trust, but Verify
Mathematicians: Trust, but VerifyMathematicians: Trust, but Verify
Mathematicians: Trust, but VerifyAndrey Karpov
 
System Hacking Tutorial #2 - Buffer Overflow - Overwrite EIP
System Hacking Tutorial #2 - Buffer Overflow - Overwrite EIPSystem Hacking Tutorial #2 - Buffer Overflow - Overwrite EIP
System Hacking Tutorial #2 - Buffer Overflow - Overwrite EIPsanghwan ahn
 
Valgrind debugger Tutorial
Valgrind debugger TutorialValgrind debugger Tutorial
Valgrind debugger TutorialAnurag Tomar
 
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Vincenzo Iozzo
 
Lets make better scripts
Lets make better scriptsLets make better scripts
Lets make better scriptsMichael Boelen
 
Handling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVMHandling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVMMin-Yih Hsu
 
Valgrind tutorial
Valgrind tutorialValgrind tutorial
Valgrind tutorialSatabdi Das
 
System Hacking Tutorial #3 - Buffer Overflow - Egg Hunting
System Hacking Tutorial #3 - Buffer Overflow - Egg HuntingSystem Hacking Tutorial #3 - Buffer Overflow - Egg Hunting
System Hacking Tutorial #3 - Buffer Overflow - Egg Huntingsanghwan ahn
 
Better Embedded 2013 - Detecting Memory Leaks with Valgrind
Better Embedded 2013 - Detecting Memory Leaks with ValgrindBetter Embedded 2013 - Detecting Memory Leaks with Valgrind
Better Embedded 2013 - Detecting Memory Leaks with ValgrindRigels Gordani
 
Rust tutorial from Boston Meetup 2015-07-22
Rust tutorial from Boston Meetup 2015-07-22Rust tutorial from Boston Meetup 2015-07-22
Rust tutorial from Boston Meetup 2015-07-22nikomatsakis
 

Was ist angesagt? (19)

Yandex may 2013 a san-tsan_msan
Yandex may 2013   a san-tsan_msanYandex may 2013   a san-tsan_msan
Yandex may 2013 a san-tsan_msan
 
Valgrind
ValgrindValgrind
Valgrind
 
Hacking 101
Hacking 101Hacking 101
Hacking 101
 
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itEvgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
 
Rust LDN 24 7 19 Oxidising the Command Line
Rust LDN 24 7 19 Oxidising the Command LineRust LDN 24 7 19 Oxidising the Command Line
Rust LDN 24 7 19 Oxidising the Command Line
 
Linux on System z debugging with Valgrind
Linux on System z debugging with ValgrindLinux on System z debugging with Valgrind
Linux on System z debugging with Valgrind
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects 100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects
 
Mathematicians: Trust, but Verify
Mathematicians: Trust, but VerifyMathematicians: Trust, but Verify
Mathematicians: Trust, but Verify
 
System Hacking Tutorial #2 - Buffer Overflow - Overwrite EIP
System Hacking Tutorial #2 - Buffer Overflow - Overwrite EIPSystem Hacking Tutorial #2 - Buffer Overflow - Overwrite EIP
System Hacking Tutorial #2 - Buffer Overflow - Overwrite EIP
 
Valgrind debugger Tutorial
Valgrind debugger TutorialValgrind debugger Tutorial
Valgrind debugger Tutorial
 
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
 
Lets make better scripts
Lets make better scriptsLets make better scripts
Lets make better scripts
 
Handling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVMHandling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVM
 
Valgrind tutorial
Valgrind tutorialValgrind tutorial
Valgrind tutorial
 
Price of an Error
Price of an ErrorPrice of an Error
Price of an Error
 
Bioinformatics v2014 wim_vancriekinge
Bioinformatics v2014 wim_vancriekingeBioinformatics v2014 wim_vancriekinge
Bioinformatics v2014 wim_vancriekinge
 
System Hacking Tutorial #3 - Buffer Overflow - Egg Hunting
System Hacking Tutorial #3 - Buffer Overflow - Egg HuntingSystem Hacking Tutorial #3 - Buffer Overflow - Egg Hunting
System Hacking Tutorial #3 - Buffer Overflow - Egg Hunting
 
Better Embedded 2013 - Detecting Memory Leaks with Valgrind
Better Embedded 2013 - Detecting Memory Leaks with ValgrindBetter Embedded 2013 - Detecting Memory Leaks with Valgrind
Better Embedded 2013 - Detecting Memory Leaks with Valgrind
 
Rust tutorial from Boston Meetup 2015-07-22
Rust tutorial from Boston Meetup 2015-07-22Rust tutorial from Boston Meetup 2015-07-22
Rust tutorial from Boston Meetup 2015-07-22
 

Andere mochten auch

Exploit Frameworks
Exploit FrameworksExploit Frameworks
Exploit Frameworksphanleson
 
Bug Hunting with Media Formats
Bug Hunting with Media FormatsBug Hunting with Media Formats
Bug Hunting with Media FormatsRussell Sanford
 
Hacking A Web Site And Secure Web Server Techniques Used
Hacking A Web Site And Secure Web Server Techniques UsedHacking A Web Site And Secure Web Server Techniques Used
Hacking A Web Site And Secure Web Server Techniques UsedSiddharth Bhattacharya
 
DrupalCamp London 2017 - Web site insecurity
DrupalCamp London 2017 - Web site insecurity DrupalCamp London 2017 - Web site insecurity
DrupalCamp London 2017 - Web site insecurity George Boobyer
 
CNIT 127 Ch 4: Introduction to format string bugs (rev. 2-9-17)
CNIT 127 Ch 4: Introduction to format string bugs (rev. 2-9-17)CNIT 127 Ch 4: Introduction to format string bugs (rev. 2-9-17)
CNIT 127 Ch 4: Introduction to format string bugs (rev. 2-9-17)Sam Bowne
 
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytes
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytesWindows Kernel Exploitation : This Time Font hunt you down in 4 bytes
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytesPeter Hlavaty
 

Andere mochten auch (8)

Exploit Frameworks
Exploit FrameworksExploit Frameworks
Exploit Frameworks
 
Bug Hunting with Media Formats
Bug Hunting with Media FormatsBug Hunting with Media Formats
Bug Hunting with Media Formats
 
Hacking A Web Site And Secure Web Server Techniques Used
Hacking A Web Site And Secure Web Server Techniques UsedHacking A Web Site And Secure Web Server Techniques Used
Hacking A Web Site And Secure Web Server Techniques Used
 
DrupalCamp London 2017 - Web site insecurity
DrupalCamp London 2017 - Web site insecurity DrupalCamp London 2017 - Web site insecurity
DrupalCamp London 2017 - Web site insecurity
 
Oracle ASM Training
Oracle ASM TrainingOracle ASM Training
Oracle ASM Training
 
CNIT 127 Ch 4: Introduction to format string bugs (rev. 2-9-17)
CNIT 127 Ch 4: Introduction to format string bugs (rev. 2-9-17)CNIT 127 Ch 4: Introduction to format string bugs (rev. 2-9-17)
CNIT 127 Ch 4: Introduction to format string bugs (rev. 2-9-17)
 
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytes
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytesWindows Kernel Exploitation : This Time Font hunt you down in 4 bytes
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytes
 
Rand rr1751
Rand rr1751Rand rr1751
Rand rr1751
 

Ähnlich wie 2.Format Strings

C format string vulnerability
C format string vulnerabilityC format string vulnerability
C format string vulnerabilitysluge
 
Format string vunerability
Format string vunerabilityFormat string vunerability
Format string vunerabilitynuc13us
 
Format string
Format stringFormat string
Format stringVu Review
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial javaTpoint s
 
Introduction to c
Introduction to cIntroduction to c
Introduction to camol_chavan
 
1.Buffer Overflows
1.Buffer Overflows1.Buffer Overflows
1.Buffer Overflowsphanleson
 
COMP 2103X1 Assignment 2Due Thursday, January 26 by 700 PM.docx
COMP 2103X1 Assignment 2Due Thursday, January 26 by 700 PM.docxCOMP 2103X1 Assignment 2Due Thursday, January 26 by 700 PM.docx
COMP 2103X1 Assignment 2Due Thursday, January 26 by 700 PM.docxdonnajames55
 
BufferOverflow - Offensive point of View
BufferOverflow - Offensive point of ViewBufferOverflow - Offensive point of View
BufferOverflow - Offensive point of ViewToe Khaing
 
Secure Coding Practices for Middleware
Secure Coding Practices for MiddlewareSecure Coding Practices for Middleware
Secure Coding Practices for MiddlewareManuel Brugnoli
 
Software Security - Static Analysis Tools
Software Security - Static Analysis ToolsSoftware Security - Static Analysis Tools
Software Security - Static Analysis ToolsEmanuela Boroș
 
Stream Based Input Output
Stream Based Input OutputStream Based Input Output
Stream Based Input OutputBharat17485
 
stackconf 2021 | Fuzzing: Finding Your Own Bugs and 0days!
stackconf 2021 | Fuzzing: Finding Your Own Bugs and 0days!stackconf 2021 | Fuzzing: Finding Your Own Bugs and 0days!
stackconf 2021 | Fuzzing: Finding Your Own Bugs and 0days!NETWAYS
 
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ..."Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...PVS-Studio
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projectsPVS-Studio
 

Ähnlich wie 2.Format Strings (20)

C format string vulnerability
C format string vulnerabilityC format string vulnerability
C format string vulnerability
 
Format string vunerability
Format string vunerabilityFormat string vunerability
Format string vunerability
 
Format string
Format stringFormat string
Format string
 
Buffer overflow
Buffer overflowBuffer overflow
Buffer overflow
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
Rust Hack
Rust HackRust Hack
Rust Hack
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
1.Buffer Overflows
1.Buffer Overflows1.Buffer Overflows
1.Buffer Overflows
 
Software Security
Software SecuritySoftware Security
Software Security
 
COMP 2103X1 Assignment 2Due Thursday, January 26 by 700 PM.docx
COMP 2103X1 Assignment 2Due Thursday, January 26 by 700 PM.docxCOMP 2103X1 Assignment 2Due Thursday, January 26 by 700 PM.docx
COMP 2103X1 Assignment 2Due Thursday, January 26 by 700 PM.docx
 
Arduino reference
Arduino referenceArduino reference
Arduino reference
 
BufferOverflow - Offensive point of View
BufferOverflow - Offensive point of ViewBufferOverflow - Offensive point of View
BufferOverflow - Offensive point of View
 
Secure Coding Practices for Middleware
Secure Coding Practices for MiddlewareSecure Coding Practices for Middleware
Secure Coding Practices for Middleware
 
Format string vunerability
Format string vunerabilityFormat string vunerability
Format string vunerability
 
Software Security - Static Analysis Tools
Software Security - Static Analysis ToolsSoftware Security - Static Analysis Tools
Software Security - Static Analysis Tools
 
Stream Based Input Output
Stream Based Input OutputStream Based Input Output
Stream Based Input Output
 
CInputOutput.ppt
CInputOutput.pptCInputOutput.ppt
CInputOutput.ppt
 
stackconf 2021 | Fuzzing: Finding Your Own Bugs and 0days!
stackconf 2021 | Fuzzing: Finding Your Own Bugs and 0days!stackconf 2021 | Fuzzing: Finding Your Own Bugs and 0days!
stackconf 2021 | Fuzzing: Finding Your Own Bugs and 0days!
 
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ..."Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects
 

Mehr von phanleson

Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Sparkphanleson
 
Firewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth FirewallsFirewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth Firewallsphanleson
 
Mobile Security - Wireless hacking
Mobile Security - Wireless hackingMobile Security - Wireless hacking
Mobile Security - Wireless hackingphanleson
 
Authentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless ProtocolsAuthentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless Protocolsphanleson
 
E-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server AttacksE-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server Attacksphanleson
 
Hacking web applications
Hacking web applicationsHacking web applications
Hacking web applicationsphanleson
 
HBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table designHBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table designphanleson
 
HBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - OperationsHBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - Operationsphanleson
 
Hbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBaseHbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBasephanleson
 
Learning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlibLearning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlibphanleson
 
Learning spark ch10 - Spark Streaming
Learning spark ch10 - Spark StreamingLearning spark ch10 - Spark Streaming
Learning spark ch10 - Spark Streamingphanleson
 
Learning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQLLearning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQLphanleson
 
Learning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a ClusterLearning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a Clusterphanleson
 
Learning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark ProgrammingLearning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark Programmingphanleson
 
Learning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your DataLearning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your Dataphanleson
 
Learning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value PairsLearning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value Pairsphanleson
 
Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Sparkphanleson
 
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about LibertagiaHướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagiaphanleson
 
Lecture 1 - Getting to know XML
Lecture 1 - Getting to know XMLLecture 1 - Getting to know XML
Lecture 1 - Getting to know XMLphanleson
 
Lecture 4 - Adding XTHML for the Web
Lecture  4 - Adding XTHML for the WebLecture  4 - Adding XTHML for the Web
Lecture 4 - Adding XTHML for the Webphanleson
 

Mehr von phanleson (20)

Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Spark
 
Firewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth FirewallsFirewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth Firewalls
 
Mobile Security - Wireless hacking
Mobile Security - Wireless hackingMobile Security - Wireless hacking
Mobile Security - Wireless hacking
 
Authentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless ProtocolsAuthentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless Protocols
 
E-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server AttacksE-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server Attacks
 
Hacking web applications
Hacking web applicationsHacking web applications
Hacking web applications
 
HBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table designHBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table design
 
HBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - OperationsHBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - Operations
 
Hbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBaseHbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBase
 
Learning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlibLearning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlib
 
Learning spark ch10 - Spark Streaming
Learning spark ch10 - Spark StreamingLearning spark ch10 - Spark Streaming
Learning spark ch10 - Spark Streaming
 
Learning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQLLearning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQL
 
Learning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a ClusterLearning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a Cluster
 
Learning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark ProgrammingLearning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark Programming
 
Learning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your DataLearning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your Data
 
Learning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value PairsLearning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value Pairs
 
Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Spark
 
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about LibertagiaHướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
 
Lecture 1 - Getting to know XML
Lecture 1 - Getting to know XMLLecture 1 - Getting to know XML
Lecture 1 - Getting to know XML
 
Lecture 4 - Adding XTHML for the Web
Lecture  4 - Adding XTHML for the WebLecture  4 - Adding XTHML for the Web
Lecture 4 - Adding XTHML for the Web
 

Kürzlich hochgeladen

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 

Kürzlich hochgeladen (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

2.Format Strings

  • 1. Course 2: Programming Issues, Section 2 Pascal Meunier, Ph.D., M.Sc., CISSP May 2004; updated July 30, 2004 Developed thanks to the support of Symantec Corporation, NSF SFS Capacity Building Program (Award Number 0113725) and the Purdue e-Enterprise Center Copyright (2004) Purdue Research Foundation. All rights reserved.
  • 2. Course 2 Learning Plan  Buffer Overflows  Format String Vulnerabilities  Code Injection and Input Validation  Cross-site Scripting Vulnerabilities  Links and Race Conditions  Temporary Files and Randomness  Canonicalization and Directory Traversal
  • 3. Learning objectives  Learn that format strings are interpreted, therefore are similar to code  Understand the definition of a format string vulnerability  Know how they happen  Know how to format strings safely with regular "C" functions  Learn other defenses against the exploitation of format string vulnerabilities
  • 4. Format String Issues: Outline  Introduction to format strings  Fundamental "C" problem  Examples  Definition  Importance  Survey of unsafe functions  Case study: analysis of cfingerd 1.4.3 vulnerabilities  Preventing format string vulnerabilities without programming  Lab: Find and fix format string vulnerabilities  Tools to find string format issues
  • 5. What is a Format String?  In “C”, you can print using a format string:  printf(const char *format, ...);  printf(“Mary has %d cats”, cats); – %d specifies a decimal number (from an int) – %s would specify a string argument, – %X would specify an unsigned uppercase hexadecimal (from an int) – %f expects a double and converts it into decimal notation, rounding as specified by a precision argument – etc...
  • 6. Fundamental "C" Problem  No way to count arguments passed to a "C" function, so missing arguments are not detected  Format string is interpreted: it mixes code and data  What happens if the following code is run?  int main () { printf("Mary has %d cats"); }
  • 7. Result  % ./a.out Mary has -1073742416 cats  Program reads missing arguments off the stack! – And gets garbage (or interesting stuff if you want to probe the stack)
  • 8. Probing the Stack  Read values off stack  Confidentiality violations  printf(“%08X”) x (X) is unsigned hexadecimal 0: with ‘0’ padding 8 characters wide: ‘0XAA03BF54’ 4 bytes = pointer on stack, canary, etc...
  • 9. User-specified Format String  What happens if the following code is run, assuming there always is an argument input by a user?  int main(int argc, char *argv[]) { printf(argv[1]); exit(0); }  Try it and input "%s%s%s%s%s%s%s%s%s" How many "%s" arguments do you need to crash it?
  • 10. Result  % ./a.out "%s%s%s%s%s%s%s" Bus error  Program was terminated by OS – Segmentation fault, bus error, etc... because the program attempted to read where it wasn't supposed to  User input is interpreted as string format (e.g., %s, %d, etc...)  Anything can happen, depending on input!  How would you correct the program?
  • 11. Corrected Program  int main(int argc, char *argv[]) { printf(“%s”, argv[1]); exit(0); }  % ./a.out "%s%s%s%s%s%s%s" %s%s%s%s%s%s%s
  • 12. Format String Vulnerabilities  Discovered relatively recently ~2000  Limitation of “C” family languages  Versatile – Can affect various memory locations – Can be used to create buffer overflows – Can be used to read the stack  Not straightforward to exploit, but examples of root compromise scripts are available on the web – "Modify and hack from example"
  • 13. Definition of a Format String Vulnerability  A call to a function with a format string argument, where the format string is either: – Possibly under the control of an attacker – Not followed by the appropriate number of arguments  As it is difficult to establish whether a data string could possibly be affected by an attacker, it is considered very bad practice to place a string to print as the format string argument. – Sometimes the bad practice is confused with the actual presence of a format string vulnerability
  • 14. How Important Are Format String Vulnerabilities?  Search NVD (icat) for “format string”: – 115 records in 2002 – 153 total in 2003 – 173 total in April 2004 – 363 in February 2006  Various applications – Databases (Oracle) – Unix services (syslog, ftp,...) – Linux “super” (for managing setuid functions) – cfingerd CVE-2001-0609  Arbitrary code execution is a frequent consequence
  • 15. Functions Using Format Strings  printf - prints to"stdout" stream  fprintf - prints to stream  warn - standard error output  err - standard error output  setproctitle - sets the invoking process's title  sprintf(char *str, const char *format, ...); – sprintf prints to a buffer – What’s the problem with that?
  • 16. Sprintf Double Whammy  format string AND buffer overflow issues!  Buffer and format string are usually on the stack  Buffer overflow rewrites the stack using values in the format string
  • 17. Better Functions Than sprintf  Note that these don't prevent format string vulnerabilities: – snprintf(char *str, size_t size, const char *format, ...);  sprintf with length check for "size" – asprintf(char **ret, const char *format, ...);  sets *ret to be a pointer to a buffer sufficiently large to hold the formatted string (note the potential memory leak).
  • 18. Custom Functions Using Format Strings  It is possible to define custom functions taking arguments similar to printf.  wu-ftpd 2.6.1 proto.h – void reply(int, char *fmt,...); – void lreply(int, char *fmt,...); – etc...  Can produce the same kinds of vulnerabilities if an attacker can control the format string
  • 19. Write Anything Anywhere  "%n" format command  Writes a number to the location specified by argument on the stack – Argument treated as int pointer  Often either the buffer being written to, or the raw input, are somewhere on the stack – Attacker controls the pointer value! – Writes the number of characters written so far  Keeps counting even if buffer size limit was reached!  “Count these characters %n”  All the gory details you don't really need to know: – Newsham T (2000) "Format String Attacks"
  • 20. Case Study: Cfingerd 1.4.3  Finger replacement – Runs as root – Pscan output: (CVE-2001-0609)  defines.h:22 SECURITY: printf call should have "%s" as argument 0  main.c:245 SECURITY: syslog call should have "%s" as argument 1  main.c:258 SECURITY: syslog call should have "%s" as argument 1  standard.c:765 SECURITY: printf call should have "%s" as argument 0  etc... (10 instances total) – Discovery: Megyer Laszlo, a.k.a. "Lez"
  • 21. Cfingerd Analysis  Most of these issues are not exploitable, but one is, indirectly at that...  Algorithm (simplified): – Receive an incoming connection  get the fingered username – Perform an ident check (RFC 1413) to learn and log the identity of the remote user – Copy the remote username into a buffer – Copy that again into "username@remote_address"  remote_address would identify attack source – Answer the finger request – Log it
  • 22. Cfingerd Vulnerabilities  A string format vulnerability giving root access: – Remote data (ident_user) is used to construct the format string: – snprintf(syslog_str, sizeof(syslog_str), "%s fingered from %s", username, ident_user ); syslog(LOG_NOTICE, (char *) syslog_str);  An off-by-one string manipulation (buffer overflow) vulnerability that – prevents remote_address from being logged (useful if attack is unsuccessful, or just to be anonymous) – Allows ident_user to be larger (and contain shell code)
  • 23. Cfingerd Buffer Overflow Vulnerability  memset(uname, 0, sizeof(uname)); for (xp=uname; *cp!='0' && *cp!='r' && *cp!='n' && strlen(uname) < sizeof(uname); cp++ ) *(xp++) = *cp;  Off-by-one string handling error – uname is not NUL-terminated! – because strlen doesn't count the NUL  It will stop copying when strlen goes reading off outside the buffer
  • 24. Direct Effect of Off-by-one Error  char buf[BUFLEN], uname[64];  "uname" and "buf" are "joined" as one string!  So, even if only 64 characters from the input are copied into "uname", string manipulation functions will work with "uname+buf" as a single entity  "buf" was used to read the response from the ident server so it is the raw input
  • 25. Consequences of Off-by-one Error 1) Remote address is not logged due to size restriction:  snprintf(bleah, BUFLEN, "%s@%s", uname, remote_addr);  Can keep trying various technical adjustments (alignments, etc...) until the attack works, anonymously 2) There's enough space for format strings, alignment characters and shell code in buf (~60 bytes for shell code):  Rooted (root compromise) when syslog call is made  i.e., cracker gains root privileges on the computer (equivalent to LocalSystem account)
  • 26. Preventing Format String Vulnerabilities 1) Always specify a format string  Most format string vulnerabilities are solved by specifying "%s" as format string and not using the data string as format string 2) If possible, make the format string a constant  Extract all the variable parts as other arguments to the call  Difficult to do with some internationalization libraries 3) If the above two practices are not possible, use defenses such as FormatGuard (see next slides) – Rare at design time – Perhaps a way to keep using a legacy application and keep costs down – Increase trust that a third-party application will be safe
  • 27. Windows  Demo code for format string exploit in Howard and Leblanc (2nd Ed.) – Same mechanisms as in UNIX-type systems – Prevented the same way
  • 28. Defenses Against Exploitation  FormatGuard – Use compiler macro tricks to count arguments passed  Special header file – Patch to glibc  Printf wrapper that counts the arguments needed by format string and verifies against the count of arguments passed – Kill process if mismatch  What’s the problem with that?
  • 29. FormatGuard Limitations  What do you do if there's a mismatch in the argument count? – Terminate it (kill)  Not complete fix, but DoS preferable to root compromise – If process is an important process that gets killed, Denial- of-Service attacks are still possible  Although if you only manage to kill a "child process" processing your own attack, there's no harm done
  • 30. FormatGuard Limitations (Cont.)  Doesn't work when program bypasses FormatGuard by using own printf version or library – wu-ftpd had its own printf – gftp used Glib library – Side note: See how custom versions of standard functions make retrofit solutions more difficult?  Code duplication makes patching more difficult Secure programming is the most secure option
  • 31. Code Scanners  Pscan searches for format string functions called with the data string as format string – Can also look for custom functions  Needs a helper file that can be generated automatically – Pscan helper file generator at http://www.cerias.purdue.edu/homes/pmeunier/dir_pscan.html – Few false positives  http://www.striker.ottawa.on.ca/~aland/pscan/
  • 32. gcc Options  -Wformat (man gcc) – "Check calls to "printf" and "scanf", etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense. " – Also checks for null format arguments for several functions  -Wformat also implies -Wnonnull  -Wformat-nonliteral (man gcc) – "If -Wformat is specified, also warn if the format string is not a string literal and so cannot be checked, unless the format function takes its format arguments as a "va_list"."
  • 33. gcc Options  -Wformat-security (man gcc) – "If -Wformat is specified, also warn about uses of format functions that represent possible security problems. At present, this warns about calls to "printf" and "scanf" functions where the format string is not a string literal and there are no format arguments, as in "printf (foo);". This may be a security hole if the format string came from untrusted input and contains %n. (This is currently a subset of what -Wformat-nonliteral warns about, but in future warnings may be added to -Wformat-security that are not included in -Wformat-nonliteral.)"  -Wformat=2 – Equivalent to -Wformat -Wformat-nonliteral -Wformat- security.
  • 34. Making gcc Look for Custom Functions  Function attributes – Keyword "__attribute__" followed by specification – For format strings, use "__attribute__ ((format))" – Example:  my_printf (void *my_object, const char *my_format, ...) __attribute__ ((format (printf, 2, 3)));  gcc can help you find functions that might benefit from a format attribute: – Switch: "-Wmissing-format-attribute" – Prints "warning: function might be possible candidate for `printf' format attribute" when appropriate
  • 35. Lab  Jared wrote a server program with examples of format string vulnerabilities – Get it from the USB keyring, web site or FTP server (follow the instructor's directions)  Usage – Compile with 'make vuln_server' – Run with './vuln_server 5555' – Open another shell window and type 'telnet localhost 5555' – Find and fix all format string vulnerabilities – Try the gcc switches
  • 36. First Lab Vulnerability  What happens when you type in the string "Hello world!"? ( it's printed back in reverse)  Type in a long string (more than 100 characters). It should crash. Where is the buffer overflow?  Fix the buffer overflow, recompile, and demonstrate that it doesn't crash on long input lines any more.  Bonus: Can you get a shell? – We didn't teach how to do that because our primary goal is to teach how to avoid the vulnerabilities, and as this lab demonstrates, you can do that without knowing how to get a shell
  • 37. Second Lab Vulnerability 1) Where is the format string problem? 2) How do you crash the program? Hint: use %s 3) How do you print the contents of memory to divulge the secret which is 0xdeadc0de? Hint: use %08x 4) Bonus: Can you get a shell?
  • 38. Third Lab Vulnerability  Latent vulnerability hidden somewhere...
  • 40. About These Slides  You are free to copy, distribute, display, and perform the work; and to make derivative works, under the following conditions. – You must give the original author and other contributors credit – The work will be used for personal or non-commercial educational uses only, and not for commercial activities and purposes – For any reuse or distribution, you must make clear to others the terms of use for this work – Derivative works must retain and be subject to the same conditions, and contain a note identifying the new contributor(s) and date of modification – For other uses please contact the Purdue Office of Technology Commercialization.  Developed thanks to the support of Symantec Corporation
  • 41. Pascal Meunier pmeunier@purdue.edu Contributors: Jared Robinson, Alan Krassowski, Craig Ozancin, Tim Brown, Wes Higaki, Melissa Dark, Chris Clifton, Gustavo Rodriguez-Rivera