Stay Hungry,Stay Foolish!

格式化字符串攻击

什么是格式化字符串攻击?

format string attack

https://www.owasp.org/index.php/Format_string_attack

首先攻击发生在 格式化字符串所涉及的函数(例如 printf), 其次用户输入字符串提交后作为格式化字符串参数执行。

攻击者可以执行代码, 读取栈空间、 写栈空间、 导致进行段错误(segment fault),或者导致其他的威胁到计算机安全和稳定性的新的行为。

 

举例子

正确例子,其中 "Bob %%x %%x" 是合法的输入。

#include  <stdio.h>
#include  <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define snprintf _snprintf

int main (int argc, char **argv)
{
    char buf [100];
    int x = 1;
    //snprintf ( buf, sizeof buf, "Bob %x %x" ) ; //bad
    snprintf ( buf, sizeof buf, "Bob %%x %%x" ) ; //good
    buf [ sizeof buf -1 ] = 0;
    printf ( "buf = %s\n", buf );
    printf ( "Buffer size is: (%d) \nData input: %s \n" , strlen (buf) , buf ) ;
    printf ( "X equals: %d/ in hex: %#x\nMemory address for x: (%p) \n" , x, x, &x) ;
    return 0 ;
}

输出

 

------ 分割线 ------

邪恶的例子,  输入 "Bob %x %x" 是非法的, 会导致snprintf函数继续读取栈数据

#include  <stdio.h>
#include  <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define snprintf _snprintf

int main (int argc, char **argv)
{
    char buf [100];
    int x = 1;
    snprintf ( buf, sizeof buf, "Bob %x %x" ) ; //bad
    //snprintf ( buf, sizeof buf, "Bob %%x %%x" ) ; //good
    buf [ sizeof buf -1 ] = 0;
    printf ( "buf = %s\n", buf );
    printf ( "Buffer size is: (%d) \nData input: %s \n" , strlen (buf) , buf ) ;
    printf ( "X equals: %d/ in hex: %#x\nMemory address for x: (%p) \n" , x, x, &x) ;
    return 0 ;
}

输出:

 

防格式化字符串攻击

1、 对于客户端提交过来的, 格式化字符串进行过滤, 将%删除, 破坏掉格式化字符串的形式。 缺点是改变客户端的提交数据完整性。但是可以保证此数据, 不管输出在格式化函数 或者 非格式化函数中, 都没有问题。

2、 对于客户端提交过来的, 格式化字符串进行转义, 对所有的%字符,前面都添加一个%, 可以保持客户端提交的数据完整性。 但是对于这种输入, 放在非格式化函数中, 会多出%。

ParametersOutputPassed as
%% % character (literal) Reference
%p External representation of a pointer to void Reference
%d Decimal Value
%c Character  
%u Unsigned decimal Value
%x Hexadecimal Value
%s String Reference
%n Writes the number of characters into a pointer Reference

3、 预防手段, 对于格式化字符串的函数, 在编码时候,需要100%注意不要将 客户端输入的 字符串作为格式化字符串, 更加严格写法, 只将常量字符串作为 格式化字符串, 即将需要的格式写死在程序中!!

附录格式化字符串涉及的函数

fprint Writes the printf to a file
printf Output a formatted string
sprintf Prints into a string
snprintf Prints into a string checking the length
vfprintf Prints the a va_arg structure to a file
vprintf Prints the va_arg structure to stdout
vsprintf Prints the va_arg to a string
vsnprintf Prints the va_arg to a string checking the length

 

posted @ 2015-03-22 09:26  lightsong  阅读(5447)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel