Try Live
Add Docs
Rankings
Pricing
Enterprise
Docs
Install
Install
Docs
Pricing
Enterprise
More...
More...
Try Live
Rankings
Add Docs
KernelSU
https://github.com/tiann/kernelsu
Admin
A Kernel based root solution for Android
Tokens:
35,668
Snippets:
282
Trust Score:
10
Update:
4 months ago
Context
Skills
Chat
Benchmark
72
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# KernelSU KernelSU is a kernel-based root solution for Android devices that provides su and root access management directly from the kernel level. Unlike traditional userspace-based root solutions, KernelSU operates within the kernel space, offering enhanced security and more granular control over root permissions. It supports Android GKI 2.0 devices (kernel 5.10+) with arm64-v8a and x86_64 architectures, and is compatible with standard Android, WSA, ChromeOS, and container-based Android systems. The project consists of three main components: a kernel module written in C that integrates with the Linux kernel, a Rust-based userspace daemon (ksud) that handles module management and system interactions, and a Kotlin/Jetpack Compose Android manager app for user-facing configuration. KernelSU introduces a metamodule system for pluggable systemless modifications, per-app profiles to restrict root access granularly, and maintains compatibility with existing root-dependent apps through a su compatibility layer. ## Kernel IOCTL Interface Kernel communication via IOCTL commands on anonymous inode file descriptor The kernel exposes an IOCTL interface through an anonymous inode file descriptor named `[ksu_driver]`. Userspace components obtain this file descriptor either by scanning `/proc/self/fd` or by making a syscall with magic numbers that trigger a kprobe hook. All kernel operations are performed through IOCTL commands on this descriptor. ```c // Get KernelSU version and status #include <sys/ioctl.h> #include <linux/ioctl.h> #define K 'K' #define KSU_IOCTL_GET_INFO _IOR(K, 2, struct ksu_get_info_cmd) struct ksu_get_info_cmd { __u32 version; // KERNEL_SU_VERSION __u32 flags; // bit 0: MODULE mode, bit 1: is_manager __u32 features; // max feature ID supported }; int fd = get_ksu_driver_fd(); // obtained via syscall or fd scan struct ksu_get_info_cmd cmd = {0}; if (ioctl(fd, KSU_IOCTL_GET_INFO, &cmd) == 0) { printf("KernelSU version: %u\n", cmd.version); printf("Module mode: %s\n", (cmd.flags & 0x1) ? "yes" : "no"); printf("Is manager: %s\n", (cmd.flags & 0x2) ? "yes" : "no"); printf("Max features: %u\n", cmd.features); } else { perror("Failed to get KernelSU info"); } ``` ## Grant Root Access Request root privileges for current process This operation elevates the current process to root by modifying its credentials in the kernel. It only succeeds if the calling UID is on the allowlist or if the caller is the manager app. Once granted, the process runs with full root privileges and the default root profile settings. ```c #define KSU_IOCTL_GRANT_ROOT _IO(K, 1) // From userspace (must be on allowlist or manager) int fd = get_ksu_driver_fd(); if (ioctl(fd, KSU_IOCTL_GRANT_ROOT, NULL) == 0) { printf("Root granted! UID: %d, GID: %d\n", getuid(), getgid()); // Process now has root privileges system("/system/bin/id"); } else { perror("Root access denied"); } ``` ## App Profile Management Manage per-app root permissions and behavior App profiles define granular permissions for each application, including whether to grant root access, custom UID/GID, capabilities, SELinux context, namespace mode, and whether to umount modules for non-root processes. Profiles are persisted in the kernel and loaded on boot. ```c #define KSU_IOCTL_GET_APP_PROFILE _IOWR(K, 11, struct ksu_get_app_profile_cmd) #define KSU_IOCTL_SET_APP_PROFILE _IOW(K, 12, struct ksu_set_app_profile_cmd) struct app_profile { char key[64]; // package name or "$" for default int current_uid; // current UID of the package int allow_su; // 1 to grant root, 0 to deny // Root profile settings int root_use_default; // use default root profile char root_template[64]; // template name if not default int uid; // target UID when rooted (0 = root) int gid; // target GID when rooted int groups_count; // number of supplementary groups int groups[32]; // supplementary group IDs unsigned long long capabilities; // capability bitmask char scontext[96]; // SELinux context int namespace_mode; // 0=inherited, 1=global, 2=individual // Non-root profile settings int non_root_use_default; // use default non-root profile int umount_modules; // 1 to umount modules for this app }; // Get profile for a package struct ksu_get_app_profile_cmd get_cmd; strcpy(get_cmd.profile.key, "com.example.app"); get_cmd.profile.current_uid = 10123; if (ioctl(fd, KSU_IOCTL_GET_APP_PROFILE, &get_cmd) == 0) { printf("Allow SU: %d\n", get_cmd.profile.allow_su); printf("Umount modules: %d\n", get_cmd.profile.umount_modules); } // Set profile to grant root with custom UID struct ksu_set_app_profile_cmd set_cmd = {0}; strcpy(set_cmd.profile.key, "com.example.rootapp"); set_cmd.profile.current_uid = 10456; set_cmd.profile.allow_su = 1; set_cmd.profile.root_use_default = 0; set_cmd.profile.uid = 2000; // run as UID 2000 when rooted set_cmd.profile.gid = 2000; strcpy(set_cmd.profile.scontext, "u:r:su:s0"); set_cmd.profile.namespace_mode = 1; // global namespace if (ioctl(fd, KSU_IOCTL_SET_APP_PROFILE, &set_cmd) == 0) { printf("Profile updated successfully\n"); } ``` ## Module Management CLI Install and manage KernelSU modules from command line The ksud daemon provides a comprehensive CLI for module management. Modules are ZIP files containing scripts and files that are unpacked to `/data/adb/modules/`. They support lifecycle scripts like `post-fs-data.sh`, `service.sh`, and `customize.sh` for systemless modifications. ```bash # Install a module from ZIP file ksud module install /sdcard/my-module.zip # List all installed modules ksud module list # Output: # example_module (enabled) - Example Module v1.0 # another_module (disabled) - Another Module v2.1 # Enable a disabled module ksud module enable example_module # Disable a module (prevents it from loading on boot) ksud module disable example_module # Remove a module completely ksud module uninstall example_module # Get info about a specific module ksud module info example_module # Output: # ID: example_module # Name: Example Module # Version: 1.0 # Author: Developer Name # Description: Sample module for testing # State: enabled ``` ## Module Structure Standard module directory layout and metadata Modules follow a specific directory structure with `module.prop` for metadata and optional lifecycle scripts. The `metamodule=1` property marks a module as a metamodule, which provides core mounting infrastructure. Only one metamodule can be active at a time. ```bash # module.prop - Module metadata id=example_module name=Example Module version=1.0.0 versionCode=1 author=Your Name description=A sample KernelSU module metamodule=0 # Directory structure: /data/adb/modules/example_module/ ├── module.prop # Required: module metadata ├── post-fs-data.sh # Optional: runs during post-fs-data ├── service.sh # Optional: runs during late_start service ├── customize.sh # Optional: runs during installation ├── uninstall.sh # Optional: runs when uninstalling ├── system/ # Optional: overlays /system │ ├── bin/ │ │ └── custom_binary │ └── etc/ │ └── custom.conf ├── system_ext/ # Optional: overlays /system_ext ├── vendor/ # Optional: overlays /vendor └── webroot/ # Optional: WebUI for module config └── index.html # Module control files: disable # Create to disable module remove # Create to mark for removal on next boot update # Create to mark as pending update # Example post-fs-data.sh #!/system/bin/sh MODDIR=${0%/*} # Run early boot tasks echo "Module loading at post-fs-data" # Mount custom files, modify system properties, etc. ``` ## SELinux Policy Patching Apply custom SELinux policy rules at runtime KernelSU allows runtime modification of SELinux policy through the kernel interface. This enables modules to add custom policy rules without rebuilding the entire policy. Policies can be applied from command line or via IOCTL. ```bash # Apply single policy rule ksud sepolicy patch "allow shell system_file file read" # Apply multiple rules from file cat > /data/local/tmp/custom.policy << EOF allow untrusted_app su process { getpgid sigchld transition } allow untrusted_app su fd use allow untrusted_app su unix_stream_socket { connectto getopt read write shutdown } type_transition untrusted_app su process su EOF ksud sepolicy apply /data/local/tmp/custom.policy # Check if policy is valid before applying ksud sepolicy check "allow system_server kernel file write" ``` ## Feature Toggles Enable or disable KernelSU features dynamically Features can be toggled at runtime to control KernelSU behavior. Common features include su compatibility mode, kernel umount functionality, and enhanced security mode. Changes take effect immediately without reboot. ```c #define KSU_IOCTL_GET_FEATURE _IOWR(K, 13, struct ksu_get_feature_cmd) #define KSU_IOCTL_SET_FEATURE _IOW(K, 14, struct ksu_set_feature_cmd) #define KSU_FEATURE_SU_COMPAT 0 #define KSU_FEATURE_KERNEL_UMOUNT 1 #define KSU_FEATURE_ENHANCED_SECURITY 2 struct ksu_get_feature_cmd { __u32 feature_id; __u64 value; __u8 supported; }; // Check if su compatibility is enabled struct ksu_get_feature_cmd get_feat = {0}; get_feat.feature_id = KSU_FEATURE_SU_COMPAT; if (ioctl(fd, KSU_IOCTL_GET_FEATURE, &get_feat) == 0) { if (get_feat.supported) { printf("SU compat: %s\n", get_feat.value ? "enabled" : "disabled"); } } // Enable enhanced security mode struct ksu_set_feature_cmd set_feat = {0}; set_feat.feature_id = KSU_FEATURE_ENHANCED_SECURITY; set_feat.value = 1; if (ioctl(fd, KSU_IOCTL_SET_FEATURE, &set_feat) == 0) { printf("Enhanced security enabled\n"); } ``` ## Rust Userspace API Interact with kernel from Rust daemon The ksud daemon provides a safe Rust wrapper around the kernel IOCTL interface. It automatically handles file descriptor installation via syscall hook and caches the driver FD for efficient repeated calls. ```rust use crate::ksucalls; // Get KernelSU version let version = ksucalls::get_version(); println!("KernelSU kernel version: {}", version); // Check if device is in safe mode if ksucalls::check_safemode() { println!("Device is in safe mode - modules disabled"); } // Report boot events to kernel ksucalls::report_post_fs_data(); // Trigger post-fs-data event ksucalls::report_boot_completed(); // Trigger boot-completed event // Get kernel features match ksucalls::get_feature(KSU_FEATURE_SU_COMPAT) { Ok((supported, value)) if supported => { println!("SU compat mode: {}", if value != 0 { "on" } else { "off" }); } _ => println!("Feature not supported"), } // Set feature value if ksucalls::set_feature(KSU_FEATURE_KERNEL_UMOUNT, 0).is_ok() { println!("Kernel umount disabled"); } ``` ## Android Manager Native Interface JNI bridge for Android app to control KernelSU The manager app communicates with the kernel through a JNI layer that wraps the IOCTL interface. The Kotlin API provides type-safe access to all kernel functionality including allowlist management, profile configuration, and feature toggles. ```kotlin import me.weishu.kernelsu.Natives // Get KernelSU version val version = Natives.version if (version == -1) { println("KernelSU not installed") } else if (Natives.requireNewKernel()) { println("Kernel version $version is too old, update required") } else { println("KernelSU version: $version") } // Get list of UIDs allowed root access val allowList: IntArray = Natives.allowList println("Allowed UIDs: ${allowList.joinToString()}") // Check if app should have modules umounted val shouldUmount = Natives.uidShouldUmount(10123) println("Should umount for UID 10123: $shouldUmount") // Get app profile val profile = Natives.getAppProfile("com.example.app", 10456) println("Allow SU: ${profile.allowSu}") println("Umount modules: ${profile.umountModules}") println("UID: ${profile.uid}, GID: ${profile.gid}") // Create and set custom profile val newProfile = Natives.Profile( name = "com.example.rootapp", currentUid = 10789, allowSu = true, rootUseDefault = false, uid = 0, // root gid = 0, groups = listOf(1015, 1023, 3003), // inet, graphics, sdcard_rw capabilities = listOf(0, 1, 2), // CAP_CHOWN, CAP_DAC_OVERRIDE, CAP_DAC_READ_SEARCH context = "u:r:su:s0", namespace = Natives.Profile.Namespace.GLOBAL.ordinal, umountModules = false ) if (Natives.setAppProfile(newProfile)) { println("Profile updated successfully") } // Feature management if (Natives.isSuEnabled()) { println("SU compat enabled") } Natives.setSuEnabled(false) // Disable su compat // Check manager status if (Natives.isManager) { println("This app is the KernelSU manager") } if (Natives.isLkmMode) { println("Running in Loadable Kernel Module mode") } ``` ## Module WebUI JavaScript API JavaScript bridge for HTML-based module configuration Modules can provide web-based configuration interfaces in the `webroot/` directory. The JavaScript API exposes functions to execute shell commands, spawn processes, query package information, and control the UI from the WebUI. ```javascript import { exec, spawn, toast, fullScreen, moduleInfo, listPackages, getPackagesInfo } from 'kernelsu'; // Execute a shell command const result = await exec('ls -la /data/adb/modules'); if (result.errno === 0) { console.log('Output:', result.stdout); } else { console.error('Error:', result.stderr); } // Execute with options const output = await exec('cat /proc/version', { cwd: '/data/local/tmp', env: { 'CUSTOM_VAR': 'value' } }); // Spawn a long-running process const child = spawn('logcat', ['-s', 'KernelSU'], { cwd: '/data/local/tmp' }); child.stdout.on('data', (data) => { console.log('stdout:', data); }); child.stderr.on('data', (data) => { console.error('stderr:', data); }); child.on('exit', (code) => { console.log(`Process exited with code ${code}`); }); child.on('error', (error) => { console.error('Process error:', error); }); // Get current module information const info = moduleInfo(); console.log('Module ID:', info.id); console.log('Module Name:', info.name); console.log('Module Version:', info.version); // List installed packages const packages = listPackages(0); // 0 = all packages packages.forEach(pkg => { console.log(`Package: ${pkg.packageName}, UID: ${pkg.uid}`); }); // Get detailed info for specific packages const pkgList = ['com.android.chrome', 'com.google.android.gms']; const details = getPackagesInfo(pkgList); details.forEach(pkg => { console.log(`${pkg.packageName}: version ${pkg.versionName}, installed at ${pkg.firstInstallTime}`); }); // Show toast message toast('Configuration saved successfully'); // Toggle fullscreen mode fullScreen(true); // Enter fullscreen fullScreen(false); // Exit fullscreen ``` ## Boot Image Patching Patch boot images to integrate KernelSU KernelSU can patch boot or init_boot images to integrate the kernel module. This is required for devices using GKI kernels where KernelSU cannot be built as a loadable module. The patching process modifies the kernel image and ramdisk. ```bash # Patch boot image ksud boot-patch \ --boot /path/to/boot.img \ --output /path/to/boot-kernelsu.img \ --kmi android14-6.1 \ --magiskboot /path/to/magiskboot # Patch with additional options ksud boot-patch \ --boot /path/to/init_boot.img \ --output /path/to/patched.img \ --kmi android13-5.15 \ --patch-backup # Create backup of original # Show supported KMI versions ksud boot-info supported-kmis # Output: # android11-5.4 # android12-5.10 # android13-5.15 # android14-6.1 # Check current KMI ksud boot-info current-kmi # Output: android14-6.1 # Show available boot partitions ksud boot-info available-partitions # Output: # boot_a # boot_b # init_boot_a # init_boot_b # Restore original boot image ksud boot-restore \ --boot /path/to/boot-kernelsu.img \ --output /path/to/boot-restored.img ``` ## Allowlist Management Control which UIDs are permitted root access The kernel maintains an allowlist of UIDs that are permitted to request root access. The allowlist is persisted to `/data/adb/ksu/.allowlist` and loaded on boot. Apps not on the allowlist cannot obtain root even if they request it. ```bash # The allowlist is typically managed through the Manager app, # but can be queried via IOCTL # From C code: #define KSU_IOCTL_GET_ALLOW_LIST _IOWR(K, 6, struct ksu_get_allow_list_cmd) #define KSU_IOCTL_UID_GRANTED_ROOT _IOWR(K, 8, struct ksu_uid_granted_root_cmd) struct ksu_get_allow_list_cmd { __u32 uids[128]; __u32 count; __u8 allow; // 1 for allowlist, 0 for denylist }; // Get allowlist struct ksu_get_allow_list_cmd cmd = {0}; cmd.allow = 1; if (ioctl(fd, KSU_IOCTL_GET_ALLOW_LIST, &cmd) == 0) { printf("Allowlist contains %u UIDs:\n", cmd.count); for (int i = 0; i < cmd.count; i++) { printf(" UID %u\n", cmd.uids[i]); } } // Check if specific UID is granted root struct ksu_uid_granted_root_cmd check = {0}; check.uid = 10456; if (ioctl(fd, KSU_IOCTL_UID_GRANTED_ROOT, &check) == 0) { printf("UID %u root access: %s\n", check.uid, check.granted ? "granted" : "denied"); } ``` ## Summary KernelSU provides a comprehensive kernel-based root solution for Android with strong security guarantees and fine-grained access control. The primary use cases include system-level app development requiring root access, systemless modifications through the module system, advanced Android customization without modifying system partitions, security research and testing, and root access management for enterprise or multi-user scenarios. The per-app profile system allows administrators to grant root to specific apps with custom UID/GID, capabilities, and SELinux contexts while denying others, and the umount feature can hide root from apps that employ root detection. Integration with KernelSU can occur at multiple levels: kernel-level integration through IOCTL commands for direct kernel communication, userspace daemon integration using the Rust ksucalls API for system services, Android app integration via the JNI/Kotlin API for root management apps, module development using ZIP-based modules with lifecycle scripts for systemless modifications, and WebUI development using the JavaScript bridge for web-based module configuration interfaces. The architecture ensures that all root access flows through the kernel, providing a centralized enforcement point that cannot be bypassed by userspace processes, and the allowlist and profile system enables zero-trust root access management where privileges are explicitly granted per app rather than globally available.