LD_PRELOAD 参考使用

发布时间 2023-05-05 09:25:06作者: 荣锋亮

以下是一个简单的试用,主要是学习下

参考示例

一个进行用户输入确认的,通过LD_PRELOAD 实现一个拦截

  • 默认代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main(){
    char inputpassword[20];
    printf("Enter the password?\n");
    scanf("%19s",inputpassword);
    if(strcmp(inputpassword,"dalong")==0){
        printf("Correct password\n");
    }
    else{
        printf("Incorrect password\n");
    }
    return 0;
}

简单说明: 需要输入dalong 之后才是正确的

  • 通过改写strcmp 结合LD_PRELOAD 拦截
int strcmp(char *s1, char *s2) {
    return 0;
}

构建共享库

gcc -shared -fPIC mystr.c -o mystr.so

进行拦截

LD_PRELOAD=./mystr.so ./demoapp

效果

说明

通过LD_PRELOAD 或者/etc/ld.so.preload 在linux 日常中还是比较常见的玩法,比如我们可以通过配置来替换glibc 默认的内存分配函数,同时还有一些
基于此模式的性能分析,当然还有一些日常的攻击(拦截系统调用,实现一些攻击破解)

参考资料

https://github.com/microsoft/mimalloc
https://github.com/jemalloc/jemalloc
https://github.com/koute/bytehound
https://stackoverflow.com/questions/426230/what-is-the-ld-preload-trick