简体   繁体   English

堆溢出攻击,此代码可能会出问题

[英]Heap Overflow attack, what can go wrong with this code

char *test(char *arg1, char* arg2){
size_t length=strlen(arg1);
char *c= malloc(length+4);
for(int i=length;i>0;i--)
   *(c+i+4)=*(arg1)^(arg2[i%8]);
*(size_t *) (c) =length;
return c;
}

Does this code suffer from heap overflow attack ? 此代码是否遭受堆溢出攻击?

Lots of things can go wrong there. 那里很多事情都会出错。 Most importantly, the expression *(c+i+4)=*(arg1)^(arg2[i%8]) is going to overflow your allocated buffer on the first iteration of the loop. 最重要的是,表达式*(c+i+4)=*(arg1)^(arg2[i%8])将在循环的第一次迭代中使分配的缓冲区溢出。

Imagine that length==1 . 想象length==1 So you'll allocate 5 bytes for c . 因此,您将为c分配5个字节。 The first time through the loop, i is equal to 1. So the expression c+i+4 resolves to c+5 , which is one byte beyond the memory you allocated. 循环中的第一次, i等于1。因此,表达式c+i+4解析为c+5 ,这比您分配的内存超出一个字节。

Other things that can go wrong: 其他可能出错的地方:

  • arg1 is an invalid pointer. arg1是无效的指针。 Your program crashes. 您的程序崩溃。
  • The string referenced by arg1 is really long, and you can't allocate enough memory for it. arg1引用的字符串确实很长,您不能为其分配足够的内存。 malloc fails and your program crashes. malloc失败,程序崩溃。
  • Memory addressed by arg2 is smaller than 8 bytes, and therefore your code is reading beyond the allocated memory. arg2寻址的内存小于8个字节,因此您的代码读取的内容超出了分配的内存。 This might not crash, but the result will be ... undefined. 这可能不会崩溃,但是结果将是...未定义。
  • You assume that size_t is 4 bytes. 您假定size_t为4个字节。 Your malloc should be malloc(length+sizeof(size_t)) . 您的malloc应该是malloc(length+sizeof(size_t))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM