2009-10-16 56 views
2

我在我的一个项目中篡改了glibc的printf()并遇到了一些问题。你能提供一些线索吗?我关心的一个问题是为什么malloc/free的相同解决方案完美无缺!使用LD_PRELOAD方法注入到printf中的问题

作为附件,“PrintfHank.c”包含我自己的printf()解决方案,它将在标准库之前预先加载;和“main.c”只是使用printf()输出一个句子。编辑两个文件后,我发出以下命令:

  1. 编译main.c中 的gcc -o -Wall主要的main.c
  2. 创建自己的库 的gcc -Wall -shared -fPIC -o PrintfHank.so PrintfHank.c -ldl
  3. 测试新图书馆 LD_PRELOAD =” $ mypath中/ PrintfHank.so” $ mypath中/主

但是我在控制台中收到了“hello world”而不是“我自己的printf”。当骇客malloc /免费功能,没关系。

我以“root”身份登录系统,并使用2.6.23.1-42.fc8-i686。任何意见将高度赞赏!

的main.c

#include <stdio.h> 

int main(void) 
{ 
    printf("hello world\n"); 

    return 0; 
} 

PrintfHank.c

#ifndef _GNU_SOURCE 
#define _GNU_SOURCE 
#endif 

#include <stdio.h> 
#include <dlfcn.h> 

static int (*orig_printf)(const char *format, ...) = NULL; 

int printf(const char *format, ...) 
{ 
if (orig_printf == NULL) 
{ 
    orig_printf = (int (*)(const char *format, ...))dlsym(RTLD_NEXT, "printf"); 
} 

// TODO: print desired message from caller. 
return orig_printf("within my own printf\n"); 
} 

回答

1

检查 1)预处理器输出。 printf的可改为SMTH其他

gcc -E main.c 

2)关于printf的符号LD_DEBUG信息和预压

LD_DEBUG=help LD_PRELOAD=”$mypath/PrintfHank.so” $mypath/main 
LD_DEBUG=all LD_PRELOAD=”$mypath/PrintfHank.so” $mypath/main 
1

变化

return orig_printf("within my own printf\n"); 

return (*orig_printf)("within my own printf\n"); 
3

这个问题是一个古老,但是:

在你main.c,你得在最后一个换行,并没有使用任何的printf的格式化功能。

如果我看的LD_DEBUG=all LD_PRELOAD=./printhack.so hello 2>&1输出(我有点重命名文件),然后在底部附近,我可以看到

17246:  transferring control: ./hello 
17246:  
17246:  symbol=puts; lookup in file=./hello [0] 
17246:  symbol=puts; lookup in file=./printhack.so [0] 
17246:  symbol=puts; lookup in file=/lib/x86_64-linux-gnu/libc.so.6 [0] 
17246:  binding file ./hello [0] to /lib/x86_64-linux-gnu/libc.so.6 [0]: normal symbol `puts' [GLIBC_2.2.5] 

printf没有实际提。 puts基本上是printf,没有格式化,最后自动换行,所以这显然是gcc通过用puts代替printf而“有帮助”的结果。

为了让你的榜样的工作,我从printf取出\n,这给了我像输出:

17114:  transferring control: ./hello 
17114:  
17114:  symbol=printf; lookup in file=./hello [0] 
17114:  symbol=printf; lookup in file=./printhack.so [0] 
17114:  binding file ./hello [0] to ./printhack.so [0]: normal symbol `printf' [GLIBC_2.2.5] 

现在我可以看到,printhack.so的确被拖在其自定义printf

或者,您也可以定义自定义puts功能以及:

static int (*orig_puts)(const char *str) = NULL; 
int puts(const char *str) 
{ 
    if (orig_puts == NULL) 
    { 
     orig_puts = (int (*)(const char *str))dlsym(RTLD_NEXT, "puts"); 
    } 

    // TODO: print desired message from caller. 
    return orig_puts("within my own puts"); 
} 
+0

有没有办法从改变函数printf()来放关闭海湾合作委员会()? – bawejakunal 2017-04-10 01:59:12