2008-12-18 83 views
4

我有一个由第三方创建的可执行模块。我想将我的代码(在单独线程中运行的看门狗)“注入”到这个过程中。代码注入 - Solaris和Linux

到目前为止,有两种可能的方式 - 一种是将我的代码作为可执行文件运行并动态地将代码加载到它上面(似乎非常困难和棘手),或者使我的代码成为共享对象,通过LD_PRELOAD并从一些静态变量构造函数初始化。

有没有更方便的方法来做到这一点? 我的操作系统是Linux x86和Solaris-SPARC。

更新:如果可能,我不想修补这个过程,但加载我的代码动态。

回答

4

听起来就像你正在寻找InjectSo。有一个Powerpoint presentation解释它是如何工作的。我还没有到处去尝试它。

+0

是的,他们的测试工作对我来说。谢谢 ! – 2008-12-18 16:25:50

0

罗布肯尼迪告诉你有关InjectSo - 这可能是你需要的。

请注意,将线程引入非线程进程将充满同步问题。如果应用程序已经线程化,那么问题就不那么严重了,但即使如此,应用程序也可能会反对它不知道的线程。

2

Hotpatch应该为你做这个。它比injectso更有能力。

0

我没有使用过提到的InjectSo,但它是一个值得注意的信息。 如果您正在寻找替代这里有一个简单的方法来注入代码:

#include <stdio.h> 
#include <sys/types.h> 
#include <pwd.h> 
int main() 
{ 
    struct passwd* pswd = getpwuid(1000); 
    if(pswd) 
     printf("%s\n", pswd->pw_name); 
    return 0; 
} 

gcc test.c -o test

#define _GNU_SOURCE 
#include <dlfcn.h> 
#include <sys/types.h> 
#include <pwd.h> 
#include <stdlib.h> 
#include <stdio.h> 

static char* hocus = "hocus pocus"; 

struct passwd *getpwuid(uid_t uid) 
{ 
    static struct passwd *(*orig_getpwuid)(uid_t uid); 
    if(!orig_getpwuid) { 
     orig_getpwuid = (struct passwd* (*)(uid_t))dlsym(RTLD_NEXT, "getpwuid"); 
    } 

    struct passwd* original_passwd = (*orig_getpwuid)(uid); 
    if(original_passwd) { 
     original_passwd->pw_name = hocus; 
    } 
    // your code here 
    return original_passwd; 
} 

gcc inject.c -shared -o libinject.so

LD_LIBRARY_PATH=. LD_PRELOAD=libinject.so ./test

运行应该说hocus pocus。您可以覆盖任意libc函数,如printf,snprintf - 只需找到该模块使用的是什么。

在“您的代码在这里”你可以开始任意线程,监督者等