为什么向容量为 128 的缓冲区发送 127 个字符时出现“分段错误”

问题描述 投票:0回答:1

我从here获取以下代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define BANNER \
  "Welcome to " LEVELNAME ", brought to you by https://exploit.education"

char *gets(char *);

void start_level() {
  char buffer[128];
  gets(buffer);
}

int main(int argc, char **argv) {
  printf("%s\n", BANNER);
  start_level();
}

我的问题是关于缓冲区存储信息的方式。
我们的缓冲区可存储 128 个字符。

当我发送 127 个字符时,出现分段错误:

user@phoenix-amd64:/opt/phoenix/amd64$ python -c 'print("A"*127)'  | ./stack-five 
Welcome to phoenix/stack-five, brought to you by https://exploit.education
Segmentation fault

但是如果我发送126个字符,就不会出现错误:

user@phoenix-amd64:/opt/phoenix/amd64$ python -c 'print("A"*126)'  | ./stack-five 
Welcome to phoenix/stack-five, brought to you by https://exploit.education
user@phoenix-amd64:

如果缓冲区的容量为128,我发送了127个字符,为什么会失败?至少应该还有一个位置吧?

我想的一件事是,也许在发送 127 个字符后,它会添加 NULL 终止符 (

\x00
),但即使发生这种情况,我们也正好有 128 个字符,那么为什么会崩溃呢?

c segmentation-fault buffer-overflow
1个回答
0
投票

' 之间存在缓冲区溢出 Python 添加的 ' 以及 c 添加的字符串所需的 ' :

[python3 -c 'print("A"*126)' | wc -c
127

我会用Python修复它:

python3 -c "print('A'*126, end='')" | wc -c
126

gets()
不安全,所以请使用
fgets()
代替。

© www.soinside.com 2019 - 2024. All rights reserved.