Chinaunix首页 | 论坛 | 博客
  • 博客访问: 33236
  • 博文数量: 15
  • 博客积分: 351
  • 博客等级: 一等列兵
  • 技术积分: 105
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-22 12:34
文章分类

全部博文(15)

文章存档

2011年(15)

我的朋友

分类: C/C++

2011-01-29 21:29:31

片段
  1. 1 #include <stdio.h>
  2.   2 #include <ctype.h>
  3.   3 #include <assert.h>
  4.   4
  5.   5 int my_atoi( const char *s )
  6.   6 {
  7.   7 int ret = 0;
  8.   8
  9.   9 assert( NULL );
  10.  10 while( *s != '\0' && isdigit(*s) ){
  11.  11 const int dig = *s - '0';
  12.  12 ret *= 10;
  13.  13 ret += dig;
  14.  14 ++s;
  15.  15 }
  16.  16 return ret;
  17.  17 }
  18.  18
  19.  19 int main( int argc , char **argv )
  20.  20 {
  21.  21 printf("\"123\" = %d\n" , my_atoi("123"));
  22.  22 printf("\"4294967297\" = %d\n" , my_atoi("4294967297"));
  23.  23
  24.  24 return 0;
  25.  25 }

  1. 05:46:41-xuk@localhost:~/svn/goodbyeworld/binary-hacks/43$gcc main.c
  2. 05:47:09-xuk@localhost:~/svn/goodbyeworld/binary-hacks/43$./a.out
  3. "123" = 123
  4. "4294967297" = 1

(signed) int 最大正整数范围 0x7fffffff ( 2147483647 dec ) . 第二次调用my_atoi()的参数大于0x7fffffff , 所以产生溢出 .

在编译时加上 -ftrapv参数 , 运行时检测到溢出后 , 会产生SIGABRT , 进程终止 .
  1. 05:47:11-xuk@localhost:~/svn/goodbyeworld/binary-hacks/43$gcc -ftrapv -g main.c
  2. 05:48:01-xuk@localhost:~/svn/goodbyeworld/binary-hacks/43$./a.out
  3. "123" = 123
  4. Aborted
用gdb运行程序 , 在产生SIGABRT程序终止后 , 看backtrace , 就可以知道源码在哪里产生整数溢出 .
  1. 05:48:02-xuk@localhost:~/svn/goodbyeworld/binary-hacks/43$gdb a.out
  2. GNU gdb Fedora (6.8-29.fc10)
  3. Copyright (C) 2008 Free Software Foundation, Inc.
  4. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
  5. This is free software: you are free to change and redistribute it.
  6. There is NO WARRANTY, to the extent permitted by law. Type "show copying"
  7. and "show warranty" for details.
  8. This GDB was configured as "i386-redhat-linux-gnu"...
  9. (gdb) r
  10. Starting program: /home/xuk/svn/goodbyeworld/binary-hacks/43/a.out
  11. "123" = 123

  12. Program received signal SIGABRT, Aborted.
  13. 0x00110416 in __kernel_vsyscall ()
  14. (gdb) bt
  15. #0 0x00110416 in __kernel_vsyscall ()
  16. #1 0x00555460 in raise (sig=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64
  17. #2 0x00556e28 in abort () at abort.c:88
  18. #3 0x08048603 in __mulvsi3 ()
  19. #4 0x080484cd in my_atoi (s=0x804870c "7") at main.c:12
  20. #5 0x08048555 in main () at main.c:22
  21. (gdb)

阅读(5077) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

xukeys2011-01-29 21:52:35

参考
[1]. <Secure Coding in C and C++>