我想覆盖 netstat -tunap 的读取功能,当我运行 netstat -tunap 的 strace 时,我感兴趣覆盖的部分就是这里的这一部分,
openat(AT_FDCWD, "/proc/net/tcp", O_RDONLY) = 3
read(3, " sl local_address rem_address "..., 4096) = 300
write(1, "tcp 0 0 192.168.32.1"..., 101tcp 0 0 192.168.32.128:59904 192.168.32.129:9001 ESTABLISHED 17186/python ) = 101
read(3, "", 4096) = 0
close(3)
我想要的是在这里看到这一行缓冲区的内容
read(3, " sl local_address rem_address "..., 4096) = 300
但是 LD_PREALOADING 的读取库仅向我打印文件描述符为 5 的读取缓冲区,这就是文件描述符为 5 的读取的样子
read(5, "unconfined\n", 4095) = 11
我该如何修复它以使其打印文件描述符为 3 的缓冲区?
这是我用于图书馆的程序,
#define _GNU_SOURCE
#include <stdio.h>
#include <dlfcn.h>
#include <unistd.h>
static ssize_t (*read_original)(int fd, void *buf, size_t count) = NULL;
ssize_t read(int fd, void *buf, size_t count) {
ssize_t result;
// Initialize the original read function if it hasn't been already
if (!read_original) {
read_original = dlsym(RTLD_NEXT, "read");
if (!read_original) {
fprintf(stderr, "Error: Unable to load the original read function\n");
return -1;
}
}
// Call the original read function
result = read_original(fd, buf, count);
// Print the buffer's contents for non-zero reads
if (result > 0 && (fd == 3 || fd == 4 || fd == 5)) {
printf("Read from fd %d, %zd bytes: ", fd, result);
for (ssize_t i = 0; i < result; ++i) {
printf("%02x ", ((unsigned char *)buf)[i]);
}
printf("\n");
}
return result;
}
我像这样创建库
gcc -shared -fPIC -o hider.so hide_read4.c -ldl
我是这样运行的
LD_PRELOAD=/path/to/lib/hider.so netstat -tunap
这是我运行此命令时的输出
Read from fd 5, 11 bytes: 75 6e 63 6f 6e 66 69 6e 65 64 0a
Read from fd 5, 11 bytes: 75 6e 63 6f 6e 66 69 6e 65 64 0a
Read from fd 5, 11 bytes: 75 6e 63 6f 6e 66 69 6e 65 64 0a
(Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.)
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 ip1:59904 ip2:9001 ESTABLISHED 17186/python
udp 0 0 ip1:68 ip3:67 ESTABLISHED -
netstat
使用 fgets()
来读取 /proc/net/tcp
中的行。使用 ltrace -netstat -tunap
工具,这些调用在 strace
输出中:
openat(AT_FDCWD, "/proc/net/tcp", O_RDONLY) = 3
read(3, " sl local_address rem_address "..., 4096) = 300
write(1, "tcp 0 0 192.168.32.1"..., 101tcp 0 0 192.168.32.128:59904 192.168.32.129:9001 ESTABLISHED 17186/python ) = 101
read(3, "", 4096) = 0
close(3)
映射到以下库调用:
fopen64("/proc/net/tcp", "r") = 0x564c3a8172a0
setvbuf(0x564c3a8172a0, 0x564c3a81a8a0, 0, 4096) = 0
fgets(" sl local_address rem_address "..., 8192, 0x564c3a8172a0) = 0x7fff68214ac0
feof(0x564c3a8172a0) = 0
.
.
.
fgets(" 28: 9801A8C0:A6D4 6310FB8E:01B"..., 8192, 0x564c3a8172a0) = 0
feof(0x564c3a8172a0) = 1
fclose(0x564c3a8172a0) = 0