这是为什么code容易受到缓冲区溢出攻击? [英] Why is this code vulnerable to buffer overflow attacks?

查看:135
本文介绍了这是为什么code容易受到缓冲区溢出攻击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int func(char* str)
{
   char buffer[100];
   unsigned short len = strlen(str);

   if(len >= 100)
   {
        return (-1);
   }

   strncpy(buffer,str,strlen(str));
   return 0;
}

这code是容易受到缓冲区溢出攻击,而我试图找出原因。我想它与 LEN 被宣布为而不是一个 INT办,但我真的不知道。

This code is vulnerable to a buffer overflow attack, and I'm trying to figure out why. I'm thinking it has to do with len being declared a short instead of an int, but I'm not really sure.

任何想法?

推荐答案

在大多数编译器的最大值无符号短 65535

On most compilers the maximum value of an unsigned short is 65535.

以上,任何价值被缠,让65536成为0,65600变成65。

Any value above that gets wrapped around, so 65536 becomes 0, and 65600 becomes 65.

这意味着选择合适的长度(如65600)的长字符串将通过检查,溢出缓冲区。

This means that long strings of the right length (e.g. 65600) will pass the check, and overflow the buffer.

使用为size_t 存储的strlen(),而不是无符号短的结果,和比较 LEN 来一个前pression直接连接codeS 缓冲区的大小。因此,例如:

Use size_t to store the result of strlen(), not unsigned short, and compare len to an expression that directly encodes the size of buffer. So for example:

char buffer[100];
size_t len = strlen(str);
if (len >= sizeof(buffer) / sizeof(buffer[0]))  return -1;
memcpy(buffer, str, len + 1);

这篇关于这是为什么code容易受到缓冲区溢出攻击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆