SlideShare a Scribd company logo
C Secure Coding: Format String Vulnerability
Igor Sobinov 2019
28.03.2019
2
Agenda
•Vulnerability definition
•Types of format vulnerability
•Vulnerability Examples
•Mitigations
3
Format String Vulnerability: Overview
Format string vulnerability class was discovered in 2001
Format string vulnerabilities are a class of vulnerabilities that take advantage of an easily
avoidable programmer error. If the programmer passes an attacker-controlled buffer as an
argument to a printf* function, the attacker can perform read and writes access to
arbitrary memory addresses.
4
Format String Vulnerability: Overview
• Format string vulnerability denial of service attacks are characterized by utilizing multiple
instances of the “%s” format specifier to read data off of the stack until the program
attempts to read data from an illegal address, which will cause the program to crash.
• Format string vulnerability reading attacks typically utilize the %x format specifier to
print sections of memory or stack that we do not normally have access to.
• Format string vulnerability writing attacks utilize the %d, %u or %x format specifiers to
overwrite the Instruction Pointer and force execution of user-supplied shell code.
5
Format String Vulnerability: Statistics
6
Format String Vulnerability: Statistics
7
Format String Vulnerability: Definition
A format string is a way of telling the C compiler how it should format numbers and other
values when it prints them or store to the buffer. It is a ASCII string used to specify and
control the representation of different variables.
In the C programming language there are a number of functions which accept a format
string as an argument: fprintf, printf, sprintf, snprintf, vfprintf, vprintf, vsprintf, vsnprintf. OS
specific: syslog, setproctitle etc.
8
Format String Vulnerability: Definition
They called variadic functions: accept variable number of arguments. Arguments are
expected to be placed on the stack.
Function prototype:
int printf(const char *format, ...);
printf (“The area code is: %d”, 505);
9
Format String Vulnerability: Format specifiers
Format Conversion specifiers:
%d The int argument is converted to signed decimal notation
%s The const char * argument is expected to be a pointer to an array of character
type
%x The unsigned int argument is converted to unsigned hexadecimal (x and X)
%p The void * pointer argument is printed in hexadecimal (as if by %#x or %#lx)
%100x Writes 100 spaces to the output before variable
%n The number of characters written so far is stored into the integer pointed to by
the corresponding argument.
%2$x Ignore the first parameter and prints the second parameter from the argument
list
10
С++ Secure Coding: Program Stack
Format string vulnerability is very close to the buffer overflow vulnerability.
• The stack itself can be viewed as a kind of buffer
• The size of that buffer is determined by the number and size of the arguments passed
to a function
• Providing a incorrect format string thus induces the program to overflow that
“buffer”
11
С++ Secure Coding: sprintf
sprintf is particularly interesting from a security standpoint because it "prints"
formatted data to a buffer. Aside from the possibility of a format-string vulnerability,
using this particular function can lead to buffer overflow vulnerabilities and should
usually be replaced with its length-checking cousin snprintf.
12
Format String Vulnerability: Examples
Format Conversion advantages:
• printf(“%1000x”, l); //Space padding is 1000 symbols
0
• printf(“%2$x”, 1, 2, 3); //Direct parameter access. Issues on gcc “invalid %N$
use detected”
2
• printf(“%200$x”)
• printf(“%n”, &some_variable); //Writes four bytes
• printf(“%hn”, &some_variable); //Writes two bytes
• printf(“%100x%2$hn”, 0, &some_variable); //Writes 100 to 2 bytes to
“some_variable”
0
13
Format String Vulnerability: Examples
• printf(“%s”): prints bytes pointed to by that stack entry
:(��•
• printf(“%d %d %d %d”): prints a series of stack entries as integers
-735270568 0 4195808 1871788256
• printf(“%08x %08x %08x %08x”): same but nicely formatted hex
27e37e68 00000000 004005e0 dadd58e0
• printf(“100% dave”): prints stack entry 4 bytes above the saved %eip because
format ignores spaces between “%d” and “d”
100-1973053272ave
• printf(“100% no way!”): writes the number 3 to address pointed to by stack
entry. %n ignores all spaces between “%” and “n”
100o way!
14
Format String Vulnerability: Attacks
• Crashing the program: printf ("%s%s%s%s%s%s%s%s%s%s%s%s");
• Viewing the stack: printf ("%08x %08x %08x %08x %08xn");
• Viewing memory at any location
• Writing an integer to nearly any location in the process memory
15
Format String Vulnerability: Program Stack
Types of programs memory:
Text: This is where the code for the program is.
Initialized data: This is where global variables that have been declared and given a value
are stored.
Uninitialized data/BSS: This is where global variables that have been declared but not
given a value are stored.
Stack: The stack keeps track of the program execution and stores local variables. We'll talk
about the stack more soon.
Heap: The heap is where dynamic memory allocation takes place. A programmer can utilize
the heap to store variables which are only needed for a short period of time and so can be
removed from memory later to optimize the program.
16
Format String Vulnerability: Program Stack
Stack keeps track of what function is being executed and the local variables that are
defined within that function.
When a function is called, a data structure called a stack frame is created.
Each function has its own stack frame which contains
• local variables for that function,
• parameters passed to the function when it was called,
• return address which specifies what instruction the program should execute next once
the function is done.
The ESP register stores current stack pointer
17
Format String Vulnerability: Program Stack (x86)
StackGrows
MemoryAddresses
18
Format String Vulnerability: Program Stack Layout
Stack Grows
19
Format String Vulnerability: Program Stack Layout
Stack Grows
20
С++ Secure Coding: Program Stack
fmt
addr
return address
saved ebp
local_var
fmt_string
return address
void test (void* addr, char* fmt)
{
int local_var = 0;
printf(fmt);
}
21
С++ Secure Coding: The exploit
arg6
arg5
arg4
arg3
arg2
fmt_string
return address
addr = 0x41414141;
fmt = “%p %p %p %p %p”
void test (void* addr, char* fmt)
{
int local = 0;
printf(fmt);
}
22
С++ Secure Coding: Program Stack
fmt
addr
return address
saved ebp
local
fmt_string
return address
addr = 0x41414141;
fmt = “%p %p %p %p %p”
void test (void* addr, char* fmt)
{
int local = 0;
printf(fmt);
}
“0x0, 0xfffca010 0x8040a10 0x41414141
0xfffeafa0”
23
С++ Secure Coding: Program Stack
fmt
addr
return address
saved ebp
local
fmt_string
return address
addr = 0x41414141;
fmt = “%4$p”
void test (void* addr, char* fmt)
{
int local = 0;
printf(fmt);
}
“0x41414141”
24
С++ Secure Coding: Program Stack
fmt
addr
return address
saved ebp
local
fmt_string
return address
addr = 0x41414141;
fmt = “%0100x%4$p”
void test (void* addr, char* fmt)
{
int local = 0;
printf(fmt);
}
“<…100 0..>0x41414141”
25
С++ Secure Coding: Program Stack
fmt
addr
return address
saved ebp
local
fmt_string
return address
addr = 0x41414141;
fmt = “%0100x%4$n”
void test (void* addr, char* fmt)
{
int local = 0;
printf(fmt);
}
“<…100 0..> write 100 to addr” written 100 to
0x41414141
26
Format String Vulnerability: Sudo format string vunerability
Feb 2012: “sudo format string vulnerability” CVE-2012-0809 allows to get root shell for
any logged in user. Most of Linux distributives were affected: Fedora, Ubuntu, Debian,
etc.
It looks like sudo creators didn’t use or ignore GCC format-related compilation flags or
warnings.
Top level projects that were affected to format string vulnerability: Axiom mail server,
Pigeon instant messenger, CUPS (Common Unix Printing System)
27
Format String Vulnerability: sudo format string vulnerability
void sudo_debug(int level, const char *fmt, ...) {
va_list ap; char *fmt2;
if (level > debug_level) return;
/* Backet fmt with program name and a newline to make it a single
write */
easprintf(&fmt2, "%s: %sn", getprogname(), fmt);
va_start(ap, fmt);
vfprintf(stderr, fmt2, ap);
va_end(ap);
efree(fmt2);
}
Here getprogname() is argv[0] and by this user controlled. So argv[0] goes to fmt2 which
then gets vfprintf()-ed to stderr. The result is a Format String vulnerability. Exploit.
28
Format String Vulnerability: Demo “Dead beef”
#include <stdio.h>
int num1 = 0xdead;
int main(int argc, char **argv){
int num2 = 0xbeef;
int *ptr = &num1;
printf(argv[1]);
if (0xabc == num1)
printf(“Global done");
if(0xdef == num2)
printf(“Local done");
printf("n num1: 0x%x [%p] num2: 0x%x [%p]n", num1, &num1, num2,
&num2);
return 0;
}
29
Format String Vulnerability: Mitigations
The good thing about format-string vulnerabilities is that they are relatively easy to find in a
source-code audit.
• Always specify a format string as part of program, not as an input. Most format string
vulnerabilities are solved by specifying “%s” as format string and not using the data
string as format string.
• Number of arguments should be the same as number of format specifiers.
• -fstack-protector (alloca and buffers > 8 bytes)
• -fstack-protector-all
• FormatGuard: Automatic Protection From printf Format String Vulnerabilities
30
Format String Vulnerability: Mitigations
Address randomization: just like the countermeasures used to protect against buffer-
overflow attacks, address randomization makes it difficult for the attackers to find out what
address they want to read/write.
# cat /proc/sys/kernel/randomize_va_space
2
# sysctl -a --pattern randomize
kernel.randomize_va_space = 2
0 = Disabled
1 = Conservative Randomization
2 = Full Randomization
To support ASLR an application should be build against “Position Independent Executable”
(PIE) support. GCC “-fPIE” option is used for it
31
Format String Vulnerability: _FORTIFY_SOURCE
• _FORTIFY_SOURCE is a kind of GCC feature test macro (man 7 feature_test_macros)
• gcc -D_FORTIFY_SOURCE=1 adds checks at compile-time only (some headers are necessary as #include
<string.h>)
• gcc -D_FORTIFY_SOURCE=2 also adds additional checks at run-time (detected buffer overflow terminates
the program)
32
Format String Vulnerability: _FORTIFY_SOURCE
*** %n in writable segment detected ***
Aborted
On x86, use of "%n" in a format string is limited to read-only memory (not stack or heap allocated strings).
*** invalid %N$ use detected ***
Aborted (core dumped)
Format string positional values are being skipped, which means their type (and size on the stack) cannot be
checked. This could cause unexpected results including stack content leaks, especially when using %n. This is
invalid, for example: printf("%2$sn", 0, "Test"); because position 1 is skipped.
33
Format String Vulnerability: Mitigations
• VC: Possible to use VC SAL annotation “_Printf_format_string_” tell compiler to validate
the format string:
#define FORMAT_STRING(p) _Printf_format_string_ p
extern void log_error(FORMAT_STRING(const char* format), ...);
• GCC: __attribute__(__format__)
format (archetype, string-index, first-to-check)
extern int
my_printf (void *my_object, const char *my_format, ...)
__attribute__ ((format (printf, 2, 3)));
34
Format String Vulnerability: Format security
-Wformat: 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.
-Wformat-security: If -Wformat is specified 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)
-Wformat-nonliteral:If -Wformat is specified, also warn if the format string is not a string
literal and so cannot be checked
35
Format String Vulnerability: Format security
Enables compile-time warnings about misuse of format strings, some of which can have security
implications.
Failure examples:
warning: format ‘%s’ expects type ‘char *’, but argument 3 has type ‘int’
For packages that aren't already building with -Wall, format character to argument types will be
checked. Verify the correct variables for a given format string.
36
Format String Vulnerability: Format security
warning: format not a string literal and no format arguments
This is caused by code that forgot to use "%s" for a *printf function. For example:
fprintf(stderr,buf);
should be:
fprintf(stderr,"%s",buf);
Disabled with -Wno-format-security or -Wformat=0 in CPPFLAGS.
37
Format String Vulnerability: Automation code scan
• RATS, the Rough Auditing Tool for Security is a free source-code scanner
• Flawfinder: Open source scanner that examines C/C++ source code and reports possible
security weaknesses
• Veracode: commercial code scanner
38
Security Design Principles
Appendix
39
References
Hacking:
The Art of
Exploitation
40
Security Design Principles

More Related Content

PPTX
Format String Attack
PPTX
Buffer overflow
ODP
Side channel attacks
PPT
Boolean and comparison_instructions
PPT
Secure hashing algorithm
PPTX
Hash function
PPTX
Buffer overflow attacks
PPT
Ch12 microprocessor interrupts
Format String Attack
Buffer overflow
Side channel attacks
Boolean and comparison_instructions
Secure hashing algorithm
Hash function
Buffer overflow attacks
Ch12 microprocessor interrupts

What's hot (20)

PPTX
Part I:Introduction to assembly language
PDF
2. Stream Ciphers
PPT
Security models
PPTX
PPTX
Cryptography
PPT
Lexical analyzer
PPTX
Trusted systems
PPT
Software Security (Vulnerabilities) And Physical Security
PPTX
Interrupts on 8086 microprocessor by vijay kumar.k
PPTX
Arm programmer's model
PPTX
An Introduction of SQL Injection, Buffer Overflow & Wireless Attack
PPTX
Buffer overflow
PPTX
Intermediate code generation1
PPTX
Public Key Cryptography
PPTX
Specification-of-tokens
PPTX
RSA Algorithm
PDF
AES-Advanced Encryption Standard
PPTX
stack in assembally language
Part I:Introduction to assembly language
2. Stream Ciphers
Security models
Cryptography
Lexical analyzer
Trusted systems
Software Security (Vulnerabilities) And Physical Security
Interrupts on 8086 microprocessor by vijay kumar.k
Arm programmer's model
An Introduction of SQL Injection, Buffer Overflow & Wireless Attack
Buffer overflow
Intermediate code generation1
Public Key Cryptography
Specification-of-tokens
RSA Algorithm
AES-Advanced Encryption Standard
stack in assembally language
Ad

Similar to C format string vulnerability (20)

PDF
Format string
ODP
Format string vunerability
PDF
2.Format Strings
PPTX
[MOSUT] Format String Attacks
PDF
CNIT 127 Ch 4: Introduction to format string bugs (rev. 2-9-17)
PDF
Wade not in unknown waters. Part two.
PDF
CNIT 127 Ch 4: Introduction to format string bugs
PDF
CNIT 127: Ch 4: Introduction to format string bugs
PPT
When good code goes bad
PPT
6 buffer overflows
PDF
CNIT 127 Ch 4: Introduction to format string bugs
PDF
Format String Vulnerability
PDF
AllBits presentation - Lower Level SW Security
PDF
Format string vunerability
PDF
CNIT 127: 4: Format string bugs
PDF
CNIT 127 Ch 4: Introduction to format string bugs
PDF
Exploitation Crash Course
PDF
Offensive cyber security: Smashing the stack with Python
PPTX
Software to the slaughter
PPTX
Pointers in C Language
Format string
Format string vunerability
2.Format Strings
[MOSUT] Format String Attacks
CNIT 127 Ch 4: Introduction to format string bugs (rev. 2-9-17)
Wade not in unknown waters. Part two.
CNIT 127 Ch 4: Introduction to format string bugs
CNIT 127: Ch 4: Introduction to format string bugs
When good code goes bad
6 buffer overflows
CNIT 127 Ch 4: Introduction to format string bugs
Format String Vulnerability
AllBits presentation - Lower Level SW Security
Format string vunerability
CNIT 127: 4: Format string bugs
CNIT 127 Ch 4: Introduction to format string bugs
Exploitation Crash Course
Offensive cyber security: Smashing the stack with Python
Software to the slaughter
Pointers in C Language
Ad

Recently uploaded (20)

PPTX
innovation process that make everything different.pptx
PDF
Smart Home Technology for Health Monitoring (www.kiu.ac.ug)
PDF
The New Creative Director: How AI Tools for Social Media Content Creation Are...
PPTX
E -tech empowerment technologies PowerPoint
PPT
isotopes_sddsadsaadasdasdasdasdsa1213.ppt
PDF
Vigrab.top – Online Tool for Downloading and Converting Social Media Videos a...
PPTX
Internet___Basics___Styled_ presentation
PPTX
Introduction to cybersecurity and digital nettiquette
PPTX
presentation_pfe-universite-molay-seltan.pptx
PPTX
Module 1 - Cyber Law and Ethics 101.pptx
PPT
Ethics in Information System - Management Information System
PDF
Tenda Login Guide: Access Your Router in 5 Easy Steps
PPTX
Introduction to Information and Communication Technology
PPTX
SAP Ariba Sourcing PPT for learning material
PDF
Introduction to the IoT system, how the IoT system works
PDF
Exploring VPS Hosting Trends for SMBs in 2025
PPTX
artificial intelligence overview of it and more
PDF
FINAL CALL-6th International Conference on Networks & IOT (NeTIOT 2025)
DOC
Rose毕业证学历认证,利物浦约翰摩尔斯大学毕业证国外本科毕业证
PPTX
INTERNET------BASICS-------UPDATED PPT PRESENTATION
innovation process that make everything different.pptx
Smart Home Technology for Health Monitoring (www.kiu.ac.ug)
The New Creative Director: How AI Tools for Social Media Content Creation Are...
E -tech empowerment technologies PowerPoint
isotopes_sddsadsaadasdasdasdasdsa1213.ppt
Vigrab.top – Online Tool for Downloading and Converting Social Media Videos a...
Internet___Basics___Styled_ presentation
Introduction to cybersecurity and digital nettiquette
presentation_pfe-universite-molay-seltan.pptx
Module 1 - Cyber Law and Ethics 101.pptx
Ethics in Information System - Management Information System
Tenda Login Guide: Access Your Router in 5 Easy Steps
Introduction to Information and Communication Technology
SAP Ariba Sourcing PPT for learning material
Introduction to the IoT system, how the IoT system works
Exploring VPS Hosting Trends for SMBs in 2025
artificial intelligence overview of it and more
FINAL CALL-6th International Conference on Networks & IOT (NeTIOT 2025)
Rose毕业证学历认证,利物浦约翰摩尔斯大学毕业证国外本科毕业证
INTERNET------BASICS-------UPDATED PPT PRESENTATION

C format string vulnerability

  • 1. C Secure Coding: Format String Vulnerability Igor Sobinov 2019 28.03.2019
  • 2. 2 Agenda •Vulnerability definition •Types of format vulnerability •Vulnerability Examples •Mitigations
  • 3. 3 Format String Vulnerability: Overview Format string vulnerability class was discovered in 2001 Format string vulnerabilities are a class of vulnerabilities that take advantage of an easily avoidable programmer error. If the programmer passes an attacker-controlled buffer as an argument to a printf* function, the attacker can perform read and writes access to arbitrary memory addresses.
  • 4. 4 Format String Vulnerability: Overview • Format string vulnerability denial of service attacks are characterized by utilizing multiple instances of the “%s” format specifier to read data off of the stack until the program attempts to read data from an illegal address, which will cause the program to crash. • Format string vulnerability reading attacks typically utilize the %x format specifier to print sections of memory or stack that we do not normally have access to. • Format string vulnerability writing attacks utilize the %d, %u or %x format specifiers to overwrite the Instruction Pointer and force execution of user-supplied shell code.
  • 7. 7 Format String Vulnerability: Definition A format string is a way of telling the C compiler how it should format numbers and other values when it prints them or store to the buffer. It is a ASCII string used to specify and control the representation of different variables. In the C programming language there are a number of functions which accept a format string as an argument: fprintf, printf, sprintf, snprintf, vfprintf, vprintf, vsprintf, vsnprintf. OS specific: syslog, setproctitle etc.
  • 8. 8 Format String Vulnerability: Definition They called variadic functions: accept variable number of arguments. Arguments are expected to be placed on the stack. Function prototype: int printf(const char *format, ...); printf (“The area code is: %d”, 505);
  • 9. 9 Format String Vulnerability: Format specifiers Format Conversion specifiers: %d The int argument is converted to signed decimal notation %s The const char * argument is expected to be a pointer to an array of character type %x The unsigned int argument is converted to unsigned hexadecimal (x and X) %p The void * pointer argument is printed in hexadecimal (as if by %#x or %#lx) %100x Writes 100 spaces to the output before variable %n The number of characters written so far is stored into the integer pointed to by the corresponding argument. %2$x Ignore the first parameter and prints the second parameter from the argument list
  • 10. 10 С++ Secure Coding: Program Stack Format string vulnerability is very close to the buffer overflow vulnerability. • The stack itself can be viewed as a kind of buffer • The size of that buffer is determined by the number and size of the arguments passed to a function • Providing a incorrect format string thus induces the program to overflow that “buffer”
  • 11. 11 С++ Secure Coding: sprintf sprintf is particularly interesting from a security standpoint because it "prints" formatted data to a buffer. Aside from the possibility of a format-string vulnerability, using this particular function can lead to buffer overflow vulnerabilities and should usually be replaced with its length-checking cousin snprintf.
  • 12. 12 Format String Vulnerability: Examples Format Conversion advantages: • printf(“%1000x”, l); //Space padding is 1000 symbols 0 • printf(“%2$x”, 1, 2, 3); //Direct parameter access. Issues on gcc “invalid %N$ use detected” 2 • printf(“%200$x”) • printf(“%n”, &some_variable); //Writes four bytes • printf(“%hn”, &some_variable); //Writes two bytes • printf(“%100x%2$hn”, 0, &some_variable); //Writes 100 to 2 bytes to “some_variable” 0
  • 13. 13 Format String Vulnerability: Examples • printf(“%s”): prints bytes pointed to by that stack entry :(��• • printf(“%d %d %d %d”): prints a series of stack entries as integers -735270568 0 4195808 1871788256 • printf(“%08x %08x %08x %08x”): same but nicely formatted hex 27e37e68 00000000 004005e0 dadd58e0 • printf(“100% dave”): prints stack entry 4 bytes above the saved %eip because format ignores spaces between “%d” and “d” 100-1973053272ave • printf(“100% no way!”): writes the number 3 to address pointed to by stack entry. %n ignores all spaces between “%” and “n” 100o way!
  • 14. 14 Format String Vulnerability: Attacks • Crashing the program: printf ("%s%s%s%s%s%s%s%s%s%s%s%s"); • Viewing the stack: printf ("%08x %08x %08x %08x %08xn"); • Viewing memory at any location • Writing an integer to nearly any location in the process memory
  • 15. 15 Format String Vulnerability: Program Stack Types of programs memory: Text: This is where the code for the program is. Initialized data: This is where global variables that have been declared and given a value are stored. Uninitialized data/BSS: This is where global variables that have been declared but not given a value are stored. Stack: The stack keeps track of the program execution and stores local variables. We'll talk about the stack more soon. Heap: The heap is where dynamic memory allocation takes place. A programmer can utilize the heap to store variables which are only needed for a short period of time and so can be removed from memory later to optimize the program.
  • 16. 16 Format String Vulnerability: Program Stack Stack keeps track of what function is being executed and the local variables that are defined within that function. When a function is called, a data structure called a stack frame is created. Each function has its own stack frame which contains • local variables for that function, • parameters passed to the function when it was called, • return address which specifies what instruction the program should execute next once the function is done. The ESP register stores current stack pointer
  • 17. 17 Format String Vulnerability: Program Stack (x86) StackGrows MemoryAddresses
  • 18. 18 Format String Vulnerability: Program Stack Layout Stack Grows
  • 19. 19 Format String Vulnerability: Program Stack Layout Stack Grows
  • 20. 20 С++ Secure Coding: Program Stack fmt addr return address saved ebp local_var fmt_string return address void test (void* addr, char* fmt) { int local_var = 0; printf(fmt); }
  • 21. 21 С++ Secure Coding: The exploit arg6 arg5 arg4 arg3 arg2 fmt_string return address addr = 0x41414141; fmt = “%p %p %p %p %p” void test (void* addr, char* fmt) { int local = 0; printf(fmt); }
  • 22. 22 С++ Secure Coding: Program Stack fmt addr return address saved ebp local fmt_string return address addr = 0x41414141; fmt = “%p %p %p %p %p” void test (void* addr, char* fmt) { int local = 0; printf(fmt); } “0x0, 0xfffca010 0x8040a10 0x41414141 0xfffeafa0”
  • 23. 23 С++ Secure Coding: Program Stack fmt addr return address saved ebp local fmt_string return address addr = 0x41414141; fmt = “%4$p” void test (void* addr, char* fmt) { int local = 0; printf(fmt); } “0x41414141”
  • 24. 24 С++ Secure Coding: Program Stack fmt addr return address saved ebp local fmt_string return address addr = 0x41414141; fmt = “%0100x%4$p” void test (void* addr, char* fmt) { int local = 0; printf(fmt); } “<…100 0..>0x41414141”
  • 25. 25 С++ Secure Coding: Program Stack fmt addr return address saved ebp local fmt_string return address addr = 0x41414141; fmt = “%0100x%4$n” void test (void* addr, char* fmt) { int local = 0; printf(fmt); } “<…100 0..> write 100 to addr” written 100 to 0x41414141
  • 26. 26 Format String Vulnerability: Sudo format string vunerability Feb 2012: “sudo format string vulnerability” CVE-2012-0809 allows to get root shell for any logged in user. Most of Linux distributives were affected: Fedora, Ubuntu, Debian, etc. It looks like sudo creators didn’t use or ignore GCC format-related compilation flags or warnings. Top level projects that were affected to format string vulnerability: Axiom mail server, Pigeon instant messenger, CUPS (Common Unix Printing System)
  • 27. 27 Format String Vulnerability: sudo format string vulnerability void sudo_debug(int level, const char *fmt, ...) { va_list ap; char *fmt2; if (level > debug_level) return; /* Backet fmt with program name and a newline to make it a single write */ easprintf(&fmt2, "%s: %sn", getprogname(), fmt); va_start(ap, fmt); vfprintf(stderr, fmt2, ap); va_end(ap); efree(fmt2); } Here getprogname() is argv[0] and by this user controlled. So argv[0] goes to fmt2 which then gets vfprintf()-ed to stderr. The result is a Format String vulnerability. Exploit.
  • 28. 28 Format String Vulnerability: Demo “Dead beef” #include <stdio.h> int num1 = 0xdead; int main(int argc, char **argv){ int num2 = 0xbeef; int *ptr = &num1; printf(argv[1]); if (0xabc == num1) printf(“Global done"); if(0xdef == num2) printf(“Local done"); printf("n num1: 0x%x [%p] num2: 0x%x [%p]n", num1, &num1, num2, &num2); return 0; }
  • 29. 29 Format String Vulnerability: Mitigations The good thing about format-string vulnerabilities is that they are relatively easy to find in a source-code audit. • Always specify a format string as part of program, not as an input. Most format string vulnerabilities are solved by specifying “%s” as format string and not using the data string as format string. • Number of arguments should be the same as number of format specifiers. • -fstack-protector (alloca and buffers > 8 bytes) • -fstack-protector-all • FormatGuard: Automatic Protection From printf Format String Vulnerabilities
  • 30. 30 Format String Vulnerability: Mitigations Address randomization: just like the countermeasures used to protect against buffer- overflow attacks, address randomization makes it difficult for the attackers to find out what address they want to read/write. # cat /proc/sys/kernel/randomize_va_space 2 # sysctl -a --pattern randomize kernel.randomize_va_space = 2 0 = Disabled 1 = Conservative Randomization 2 = Full Randomization To support ASLR an application should be build against “Position Independent Executable” (PIE) support. GCC “-fPIE” option is used for it
  • 31. 31 Format String Vulnerability: _FORTIFY_SOURCE • _FORTIFY_SOURCE is a kind of GCC feature test macro (man 7 feature_test_macros) • gcc -D_FORTIFY_SOURCE=1 adds checks at compile-time only (some headers are necessary as #include <string.h>) • gcc -D_FORTIFY_SOURCE=2 also adds additional checks at run-time (detected buffer overflow terminates the program)
  • 32. 32 Format String Vulnerability: _FORTIFY_SOURCE *** %n in writable segment detected *** Aborted On x86, use of "%n" in a format string is limited to read-only memory (not stack or heap allocated strings). *** invalid %N$ use detected *** Aborted (core dumped) Format string positional values are being skipped, which means their type (and size on the stack) cannot be checked. This could cause unexpected results including stack content leaks, especially when using %n. This is invalid, for example: printf("%2$sn", 0, "Test"); because position 1 is skipped.
  • 33. 33 Format String Vulnerability: Mitigations • VC: Possible to use VC SAL annotation “_Printf_format_string_” tell compiler to validate the format string: #define FORMAT_STRING(p) _Printf_format_string_ p extern void log_error(FORMAT_STRING(const char* format), ...); • GCC: __attribute__(__format__) format (archetype, string-index, first-to-check) extern int my_printf (void *my_object, const char *my_format, ...) __attribute__ ((format (printf, 2, 3)));
  • 34. 34 Format String Vulnerability: Format security -Wformat: 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. -Wformat-security: If -Wformat is specified 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) -Wformat-nonliteral:If -Wformat is specified, also warn if the format string is not a string literal and so cannot be checked
  • 35. 35 Format String Vulnerability: Format security Enables compile-time warnings about misuse of format strings, some of which can have security implications. Failure examples: warning: format ‘%s’ expects type ‘char *’, but argument 3 has type ‘int’ For packages that aren't already building with -Wall, format character to argument types will be checked. Verify the correct variables for a given format string.
  • 36. 36 Format String Vulnerability: Format security warning: format not a string literal and no format arguments This is caused by code that forgot to use "%s" for a *printf function. For example: fprintf(stderr,buf); should be: fprintf(stderr,"%s",buf); Disabled with -Wno-format-security or -Wformat=0 in CPPFLAGS.
  • 37. 37 Format String Vulnerability: Automation code scan • RATS, the Rough Auditing Tool for Security is a free source-code scanner • Flawfinder: Open source scanner that examines C/C++ source code and reports possible security weaknesses • Veracode: commercial code scanner