格式化字符串攻击

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

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
%pExternal representation of a pointer to voidReference
%dDecimalValue
%cCharacter 
%uUnsigned decimalValue
%xHexadecimalValue
%sStringReference
%nWrites the number of characters into a pointerReference

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

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

fprintWrites the printf to a file
printfOutput a formatted string
sprintfPrints into a string
snprintfPrints into a string checking the length
vfprintfPrints the a va_arg structure to a file
vprintfPrints the va_arg structure to stdout
vsprintfPrints the va_arg to a string
vsnprintfPrints the va_arg to a string checking the length

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值