代码之家  ›  专栏  ›  技术社区  ›  Dmitry Khalatov

代码注入-Solaris和Linux

  •  4
  • Dmitry Khalatov  · 技术社区  · 16 年前

    我有一个由第三方创建的可执行模块。我想“注入”我的代码(类似于在单独线程中运行的看门狗)到这个进程中。

    到目前为止,有两种可能的方法-一种是以可执行文件的形式运行代码,并在其上动态加载进程(似乎非常困难和棘手),或者使代码成为共享对象,通过LD_PRELOAD加载代码,然后从某个静态变量构造函数初始化。

    有没有更方便的方法? 我的操作系统是Linux x86和Solaris SPARC。

    4 回复  |  直到 16 年前
        1
  •  4
  •   Rob Kennedy    16 年前

    听起来你在找 InjectSo . 有一个 Powerpoint presentation 这就解释了它的工作原理。我还没来得及试一下。

        2
  •  2
  •   animuson    13 年前

    Hotpatch 我应该为你做这件事。它比以前更有能力。

        3
  •  0
  •   Jonathan Leffler    16 年前

    罗伯·肯尼迪告诉过你,那可能是你需要的。

        4
  •  0
  •   RushPL    13 年前

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

    #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 -只要找到模块使用的是什么。

    在“你的代码在这里”,你可以启动任意线程,看门狗等。