前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >劫持系统函数Demo

劫持系统函数Demo

作者头像
Walton
发布2018-04-13 16:27:01
1.2K0
发布2018-04-13 16:27:01
举报
文章被收录于专栏:KubernetesKubernetes

以下内容是劫持glib.c中标准printf函数的方法。是这篇 Docker容器内的监控命令数据修正思路的基础知识。对LD_PRELOAD熟悉可以不看。

##劫持printf函数的Demo

[root@garnett-vm-1-3nskg test_ld]# ls hijack_printf.c printf_hello.c

root@garnett-vm-1-3nskg test_ld]# cat printf_hello.c

代码语言:javascript
复制
#include <stdio.h>
	main()
	{
	        printf("hello garnett.wang!");
	}

[root@garnett-vm-1-3nskg test_ld]# cat hijack_printf.c

代码语言:javascript
复制
#define _GNU_SOURCE

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


int printf(const char *format, ...)
{
va_list list;
        char *parg;
        typeof(printf) *old_printf;

        // format variable arguments
        va_start(list, format);
        vasprintf(&parg, format, list);
        va_end(list);

        //DO HERE SOMETHING VERY EVIL

        // get a pointer to the function "printf"
        old_printf = dlsym(RTLD_NEXT, "printf");
        (*old_printf)("I have hijacked printf : %s", parg); // and we call the function with previous arguments

        free(parg);
}

注意:在 #include <dlfcn.h>前加 #define _GNU_SOURCE,因为RTLD_NEXTposix标准中包含的。

[root@garnett-vm-1-3nskg test_ld]# gcc printf_hello.c -o printf_hello [root@garnett-vm-1-3nskg test_ld]# ls hijack_printf.c printf_hello printf_hello.c

###劫持之前: [root@garnett-vm-1-3nskg test_ld]# ./printf_hello hello garnett.wang!

编译源代码生成劫持so文件: [root@garnett-vm-1-3nskg test_ld]# gcc -shared -fPIC hijack_printf.c -o libhijack_printf.so -ldl [root@garnett-vm-1-3nskg test_ld]# ls hijack_printf.c libhijack_printf.so printf_hello printf_hello.c

###配置LD_PRELOAD: [root@garnett-vm-1-3nskg test_ld]# export LD_PRELOAD=pwd/libhijack_printf.so [root@garnett-vm-1-3nskg test_ld]# echo $LD_PRELOAD /root/test_ld/libhijack_printf.so

###劫持之后: [root@garnett-vm-1-3nskg test_ld]# ./printf_hello I have hijacked printf : hello garnett.wang!

###查看ld dependency: [root@garnett-vm-1-3nskg test_ld]# ldd libhijack_printf.so linux-vdso.so.1 => (0x00007fff0fcfe000) libdl.so.2 => /lib64/libdl.so.2 (0x00007fb30bd30000) libc.so.6 => /lib64/libc.so.6 (0x00007fb30b99b000) /lib64/ld-linux-x86-64.so.2 (0x00007fb30c13c000)

[root@garnett-vm-1-3nskg test_ld]# ldd printf_hello linux-vdso.so.1 => (0x00007fff0c5ff000) /root/test_ld/libhijack_printf.so (0x00007fc6329a8000) libc.so.6 => /lib64/libc.so.6 (0x00007fc63260d000) libdl.so.2 => /lib64/libdl.so.2 (0x00007fc632409000) /lib64/ld-linux-x86-64.so.2 (0x00007fc632baa000)

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器镜像服务
容器镜像服务(Tencent Container Registry,TCR)为您提供安全独享、高性能的容器镜像托管分发服务。您可同时在全球多个地域创建独享实例,以实现容器镜像的就近拉取,降低拉取时间,节约带宽成本。TCR 提供细颗粒度的权限管理及访问控制,保障您的数据安全。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档