KernelSU on begonia: What the Patch Actually Does to Your Kernel
The KernelSU manager app makes root look straightforward: flash, approve apps, done. The kernel side is less clean. On begonia (Redmi Note 8 Pro, Helio G90T, kernel 4.14) with MediaTek's full vendor patch stack, integrating KernelSU without breaking SELinux or the OOM killer took more than the standard instructions suggested. Here's what's actually happening at each step.
What KernelSU Is (and Is Not)
Not Magisk. Magisk patches the boot image, injects an init overlay into the second-stage init process, and implements root by overlaying a /sbin/.magisk filesystem. It works without touching kernel source.
KernelSU works the other way: it's a set of kernel patches plus a userspace manager. Root is granted through a kernel-level security hook, not a filesystem overlay or ptrace trick. The boot image is not patched. The init process is not injected. Instead, when a privileged process calls execve() on the su binary, the kernel intercepts the call and evaluates whether to grant elevated credentials based on an in-kernel allow list.
The practical difference: KernelSU is much harder to detect by userspace attestation (the credential change happens in kernel space with no userspace intermediary), but it requires source-level changes to the kernel and cannot be installed by a recovery-only flashable zip.
Three integration methods for out-of-tree kernels:
-
GKI hooks (upstream recommended):
EXPORT_SYMBOL(ksu_handle_*)functions called from specific points in the kernel. Only works on GKI 2.0 kernels (5.10+, official Android kernel infrastructure). Not available on begonia's 4.14 tree. -
kprobes: Attach a probe to existing kernel functions (
commit_creds,security_inode_permission) without modifying them. RequiresCONFIG_KPROBES=yandCONFIG_KALLSYMS_ALL=y. Works on 4.14 with caveats. -
Manual patch: Directly add KernelSU call sites into the kernel source (in
fs/exec.c,fs/open.c, etc.). Most reliable on vendor trees. This is what Nova-Kernels uses for begonia.
The Hook Mechanism: kprobes vs Manual Patch
Why kprobes alone wasn't enough on begonia
kprobes works by replacing the first byte of a target function with a int 3 breakpoint instruction (on x86) or an undefined instruction trap (on ARM64). When the CPU hits it, it jumps to the kprobe handler, runs the pre-handler, restores the original instruction, single-steps it, then continues. This is elegant and requires zero source modification.
The begonia problem: CONFIG_KALLSYMS_ALL was not enabled in the stock defconfig. Without it, the kernel's symbol table doesn't include static functions, and kallsyms_lookup_name() can't resolve them. KernelSU's kprobes path needs to find commit_creds and security_inode_permission by name. commit_creds is exported (it's in kernel/cred.c as EXPORT_SYMBOL), but security_inode_permission is not; it's a static wrapper in security/security.c.
Enabling CONFIG_KALLSYMS_ALL fixes the symbol resolution but doubles the kernel binary size (adds every static symbol name to the image). MTK's stock build was already at the edge of boot partition size limits. We enabled it anyway and shaved elsewhere (CONFIG_DEBUG_INFO=n saves more than KALLSYMS_ALL costs), but it's a real constraint on tighter devices.
The second problem: begonia ships with MediaTek's mt_privid_flt (private ID filter) hook inside the credential grant path. This hook checks whether a process is allowed to call commit_creds with elevated credentials, based on a vendor-maintained allowlist in a TEE-backed secure element. When KernelSU's kprobe pre-handler returns, the original commit_creds runs, and mt_privid_flt runs inside it, sees an unexpected credential escalation, and logs it. On some firmware versions, it also raises a security event that triggers sec_restrict_fork() to kill the process on next fork().
This is why we use the manual patch method for begonia instead of kprobes.
What the Manual Patch Actually Does
The patch adds five call sites to the kernel. The critical one is in fs/exec.c:
/* fs/exec.c -- simplified version of the KernelSU patch */
#ifdef CONFIG_KSU
extern int ksu_handle_execveat(int *fd, struct filename **filename_ptr,
void *argv, void *envp, int *flags);
#endif
static int do_execveat_common(int fd, struct filename *filename,
struct user_arg_ptr argv,
struct user_arg_ptr envp,
int flags)
{
#ifdef CONFIG_KSU
ksu_handle_execveat(&fd, &filename, &argv, &envp, &flags);
#endif
/* ... rest of exec path ... */
}
And in fs/open.c for faccessat:
#ifdef CONFIG_KSU
extern int ksu_handle_faccessat(int *dfd, const char __user **filename_user,
int *mode, int *flags);
#endif
long do_faccessat(int dfd, const char __user *filename, int mode, int flags)
{
#ifdef CONFIG_KSU
ksu_handle_faccessat(&dfd, &filename, &mode, &flags);
#endif
/* ... */
}
ksu_handle_execveat() is where the actual root decision happens.
The Root Grant: What Actually Changes in the Kernel
This is the part most writeups skip. KernelSU doesn't just call setuid(0). That's a userspace syscall. What it does is modify the calling process's task_struct credentials directly in kernel space, using prepare_creds() and commit_creds():
/* kernel/ksu/src/sucompat.c */
int ksu_handle_execveat_sucompat(int *fd, struct filename **filename_ptr,
void *argv, void *envp, int *flags)
{
struct filename *filename;
const char su[] = "su";
if (unlikely(!ksu_enabled))
return 0;
filename = *filename_ptr;
if (IS_ERR(filename))
return 0;
/* Check if this is an exec of "su" */
if (memcmp(filename->name + filename->len - sizeof(su) + 1,
su, sizeof(su)) != 0)
return 0;
/* Check allow list (stored in kernel memory, managed by manager app) */
if (!ksu_is_allow_uid(current_uid().val))
return 0;
/* Grant root: modify current task's credentials */
struct cred *new = prepare_creds();
if (!new)
return -ENOMEM;
new->uid = GLOBAL_ROOT_UID;
new->gid = GLOBAL_ROOT_GID;
new->euid = GLOBAL_ROOT_UID;
new->egid = GLOBAL_ROOT_GID;
new->suid = GLOBAL_ROOT_UID;
new->sgid = GLOBAL_ROOT_GID;
new->fsuid = GLOBAL_ROOT_UID;
new->fsgid = GLOBAL_ROOT_GID;
/* Set all capabilities */
cap_set_full(new->cap_effective);
cap_set_full(new->cap_permitted);
cap_set_full(new->cap_inheritable);
cap_set_full(new->cap_ambient);
cap_set_full(new->cap_bset);
commit_creds(new);
return 0;
}
prepare_creds() allocates a copy of the current credential set. commit_creds() atomically installs it into current->cred. From this point, the process has UID 0 and all capabilities. This is the same code path used by su in a traditional Linux environment. The difference is that it happens inside the kernel, without any setuid binary or PAM interaction.
The allow list check (ksu_is_allow_uid()) queries an in-kernel hash table populated by the KernelSU manager app via a /proc/ interface. No userspace daemon is needed at grant time.
LSM Integration
KernelSU registers itself as a Linux Security Module. The LSM framework in the kernel is a set of hooks inserted at security-critical points: file open, credential change, socket bind, etc. SELinux is the dominant LSM in Android. Other modules stack on top or alongside it.
/* kernel/ksu/src/lsm.c */
static struct security_hook_list ksu_hooks[] = {
LSM_HOOK_INIT(task_alloc, ksu_task_alloc),
LSM_HOOK_INIT(task_free, ksu_task_free),
LSM_HOOK_INIT(bprm_check_security, ksu_bprm_check_security),
};
static struct lsm_info __lsm_info_ksu = {
.name = "ksu",
.init = ksu_lsm_init,
.order = LSM_ORDER_LAST,
};
LSM_ORDER_LAST means KernelSU's hooks run after SELinux has already made its decision. This is intentional. KernelSU doesn't want to override SELinux context decisions for normal processes. It only cares about the specific su exec path.
The bprm_check_security hook runs during execve(), after the binary has been set up but before the process's credentials are finalized. This is where KernelSU checks the allow list and calls commit_creds() if appropriate.
The begonia-Specific Headaches
CONFIG_KALLSYMS_ALL: Not in stock begonia defconfig. Required for kprobes path to resolve static symbols. Enabled in Nova-Kernels build. Adds ~400KB to the kernel image. Acceptable tradeoff.
sec_restrict_fork(): MTK's vendor function that runs in the copy_process() path after a credential change. It checks whether the newly forked process's UID differs from its parent in unexpected ways and can kill the child process. When KernelSU grants UID 0 to a shell process that then forks a subprocess, sec_restrict_fork() sees the fork of a UID-0 process spawned from a non-UID-0 parent and logs a security event. On some firmware builds (not all; this is firmware version dependent), the event triggers a kill. The fix is to set the PF_NO_SETAFFINITY flag on the KernelSU-granted process before it forks, which sec_restrict_fork() checks as an exemption condition.
OOM killer interaction: Processes with UID 0 have their OOM score adjusted by the Android low memory killer to -1000 (never kill). KernelSU-granted processes inherit this after commit_creds. On begonia with 6GB RAM, this means a misbehaving root process can sit unkillable while other apps are being evicted. Not a bug per se, but something to be aware of. We added a KernelSU option to not reset the OOM score, so root apps still get adjusted by the LMKD like normal apps.
KernelSU detection by apps: Several apps (banking apps, game anticheats) check for KernelSU by looking for:
- The
/proc/sys/kernel/ksusysctl entry - The
ksustring in/proc/[pid]/statussecurity attributes - The
KSUbuild tag in kernel version string
KernelSU has a hide feature that addresses most of these, but it's an arms race. The relevant kernel config option is CONFIG_KSU_HIDE_KSU.
Verification
After flashing a kernel with KernelSU patches:
# Check if KernelSU is recognized
adb shell uname -a
# Should include something like: #1 SMP PREEMPT ... ksu
# Check kernel log for KSU init
adb shell dmesg | grep -i ksu
# Expected:
# [ 3.421] KernelSU: version: 11895
# [ 3.422] KernelSU: allow uid count: 1
# Verify allow list is accessible
adb shell ls -la /proc/sys/kernel/ksu
# After installing manager app and allowing root:
adb shell su -c id
# uid=0(root) gid=0(root) groups=0(root) context=u:r:su:s0
A dmesg entry like KernelSU: umh support is disabled, fallback to compat mode means the usermode helper is not available and KernelSU is using the compatibility path. This is normal on strict vendor kernels. Root still works; the manager app communication path is slightly different.
If dmesg | grep ksu returns nothing after boot, the patch didn't compile in. Check that CONFIG_KSU=y is in the defconfig and that the source patch applied cleanly (common failure point: the do_execveat_common() function signature changed between 4.14.x patch levels).
The main lesson from doing this on begonia: vendor security hooks are not documented, not standardized, and not consistent across firmware versions. The best approach is to read the vendor's security/ directory additions carefully before assuming any upstream integration guide applies directly to your device tree.