Rooting, Flashing, & Bootloader Exploits

Crafting Custom SU Wrapper Scripts: Extending Root Functionality on Android

Google AdSense Native Placement - Horizontal Top-Post banner

Introduction: The Power of SU and Beyond

The su binary is the gateway to root privileges on Android, allowing elevated commands to run system-wide. While powerful, its default behavior is straightforward: execute a command as root. For advanced users, developers, and system integrators, this simplicity can be a limitation. This guide delves into the creation of custom SU wrapper scripts, a sophisticated technique to intercept, augment, and control root commands, thereby extending the core functionality of your rooted Android device.

By implementing wrapper scripts, you can introduce custom logging, enforce conditional execution, manipulate environment variables, and even redirect command output, transforming simple root calls into intelligent, context-aware operations. We’ll explore the fundamentals of the su binary, the rationale behind wrappers, and provide practical, step-by-step examples for building and deploying these powerful tools.

Understanding the SU Binary’s Core Mechanism

At its heart, the su (substitute user) binary is designed to switch the current user context to another, most commonly to the root user (UID 0). When you execute su -c "command", the following typically occurs:

  1. The su binary is invoked by an unprivileged user (e.g., shell user, an app).
  2. It checks if the requesting user has permission to switch to root. On rooted devices, a superuser management app (like MagiskSU or SuperSU) mediates this request.
  3. Upon approval, su forks a new process, sets its effective UID and GID to 0 (root), and then executes the specified “command” within this elevated context.
  4. The output of “command” is typically returned to the calling process.

This process is efficient but lacks flexibility. There’s no built-in way to log every root command, add pre-execution checks, or modify the execution environment dynamically without explicitly bundling such logic into every root-requiring application or script.

The Rationale for Custom SU Wrapper Scripts

Custom SU wrappers address the limitations of the direct su invocation by acting as an intermediary. Instead of directly calling su -c "command", you call your wrapper script, which then performs additional logic before or after invoking the actual su binary. This allows for:

  • Advanced Logging: Record every root command executed, who executed it, and when, invaluable for security audits or debugging.
  • Pre/Post-Execution Hooks: Inject custom logic before a command runs (e.g., check disk space) or after (e.g., clean up temporary files).
  • Environment Manipulation: Set specific environment variables (PATH, LD_LIBRARY_PATH, custom variables) for root processes, ensuring consistent execution across different contexts.
  • Conditional Execution: Implement logic to allow or deny certain root commands based on various criteria (time of day, network state, calling application).
  • Custom Command Aliases/Redirection: Intercept specific commands and execute alternative or enhanced versions.

Crafting a Basic SU Wrapper Script

Let’s start with a simple pass-through wrapper. This script will simply accept all arguments and pass them directly to the real su binary.

Create a file, for example, /data/local/bin/my_su_wrapper.sh:

#!/system/bin/sh# This is a basic SU wrapper script. It simply passes all arguments to the real su binary.# Ensure your PATH is set correctly or provide the full path to the real su.REAL_SU="/sbin/su" # Adjust this path based on your root solution (e.g., /data/adb/magisk/su for Magisk)if [ ! -f "$REAL_SU" ]; then    echo "Error: Real su binary not found at $REAL_SU" >&2    exit 1fi# Execute the real su with all arguments passed to this wrapperexec "$REAL_SU" "$@"

Make it executable:

adb shellchmod 0755 /data/local/bin/my_su_wrapper.sh

Now, if you were to call /data/local/bin/my_su_wrapper.sh -c "id", it would behave identically to calling /sbin/su -c "id".

Implementing Advanced Wrapper Techniques

1. Logging All Root Commands

This is one of the most common and valuable uses. We’ll log the timestamp, the calling user, and the command executed.

#!/system/bin/shREAL_SU="/sbin/su"LOG_FILE="/data/local/tmp/su_activity.log"# Ensure log directory exists (adjust permissions if needed)mkdir -p "$(dirname "$LOG_FILE")" &>/dev/null# Get calling user (if available, otherwise fallback to shell user)CALLING_USER="$(logname 2>/dev/null || whoami)"if [ -z "$CALLING_USER" ]; then    CALLING_USER="unknown"fi# Log the command before executionecho "$(date '+%Y-%m-%d %H:%M:%S') [USER:$CALLING_USER] CMD: '$@'" >> "$LOG_FILE"# Execute the real su with all argumentsexec "$REAL_SU" "$@"

2. Pre-Execution Checks (Example: Block Specific Commands)

You can add logic to prevent certain commands from being executed by root.

#!/system/bin/shREAL_SU="/sbin/su"LOG_FILE="/data/local/tmp/su_activity.log"# Command arguments passed to the wrapperCMD_ARGS="$@"# Simple check: Block 'rm -rf /' for safetyif echo "$CMD_ARGS" | grep -q 'rm -rf /'; then    echo "WARNING: Attempted to execute dangerous command: '$CMD_ARGS' - BLOCKED!" >&2    echo "$(date '+%Y-%m-%d %H:%M:%S') [BLOCKED] Dangerous command: '$CMD_ARGS'" >> "$LOG_FILE"    exit 1fi# Log and execute if not blockedecho "$(date '+%Y-%m-%d %H:%M:%S') [EXECUTED] CMD: '$CMD_ARGS'" >> "$LOG_FILE"exec "$REAL_SU" "$CMD_ARGS"

3. Environment Variable Manipulation

You might need specific environment variables set for a root process, e.g., a custom PATH or `LD_LIBRARY_PATH`.

#!/system/bin/shREAL_SU="/sbin/su"# Add custom paths to the beginning of the PATH environment variableexport PATH="/data/local/bin:/usr/local/sbin:$PATH"# Set a custom library pathexport LD_LIBRARY_PATH="/data/local/lib:$LD_LIBRARY_PATH"# Execute the real su with the modified environmentexec "$REAL_SU" "$@"

Deployment Strategies and Permissions

For a wrapper script to be truly effective, it needs to be called instead of the original su binary. The most robust method, especially on modern Android, involves using a Magisk module for systemless integration.

Magisk Module Deployment (Recommended)

  1. Create a Magisk Module Structure:
  2. my_su_wrapper_module/├── module.prop├── customize.sh├── post-fs-data.sh└── system/    └── bin/        └── su
  3. module.prop: Basic module info.
  4. id=my_su_wrappername=Custom SU Wrapper Scriptversion=v1.0author=YourName/Handledescription=Interceptors and enhances su commands.
  5. customize.sh (Optional, for more complex installs): You might not need this for a simple `su` replacement.
  6. post-fs-data.sh: This script runs early during boot. Here, we’ll replace the actual `su` binary.
  7. #!/system/bin/shMODPATH="${0%/*}"# Create a bind mount so our custom script is executed when 'su' is called.mount -o bind "$MODPATH/system/bin/su" /sbin/su

    Note: Magisk already handles bind mounts for `/sbin/su` via its internal mechanisms. The `system/bin/su` inside your module will *replace* Magisk’s `su` *for applications that call it directly*. Your wrapper needs to then call Magisk’s *original* `su` binary (often found at `/data/adb/magisk/su`).

  8. Your Wrapper Script (system/bin/su inside the module):
  9. #!/system/bin/sh# The REAL_SU path for Magisk is usually /data/adb/magisk/suREAL_SU="/data/adb/magisk/su"LOG_FILE="/data/local/tmp/magisk_su_activity.log"# ... (your wrapper logic from above) ...# Final executionexec "$REAL_SU" "$@"
  10. Permissions: Ensure your module’s system/bin/su script has correct permissions within the module:
  11. chmod 0755 my_su_wrapper_module/system/bin/su
  12. Install: Zip the my_su_wrapper_module folder and install it via the Magisk Manager.

Direct System Modification (Not Recommended on Modern Android)

This method involves directly modifying `/system/bin/su` or `/sbin/su`. It is highly discouraged due to SELinux implications, potential for bootloops, and being overwritten by OTA updates.

  • Rename original su: mv /sbin/su /sbin/su.real
  • Place your wrapper: cp /path/to/my_su_wrapper.sh /sbin/su
  • Set permissions: chmod 0755 /sbin/su and chown root:shell /sbin/su
  • Modify wrapper to call /sbin/su.real

SELinux Considerations: Android’s Security-Enhanced Linux (SELinux) policies are strict. When you place your wrapper, it needs the correct SELinux context (e.g., `u:object_r:su_exec:s0`). Magisk modules simplify this by leveraging Magisk’s own context handling and bind-mounts. If you manually modify the system, you’d need to set the context using `chcon` after placement, which is often difficult without prior policy adjustments.

Practical Use Cases and Examples

  • Automated Network Firewall: On boot, a wrapper could check network state and apply complex `iptables` rules only when connected to specific Wi-Fi networks.
  • Secure Command Execution: A wrapper could enforce that certain sensitive commands (e.g., modifying `/system`) can only be executed by specific applications or users, or only after a secondary authentication prompt.
  • Performance Tuning: Automatically adjust CPU governor, I/O scheduler, or RAM parameters for gaming apps by detecting their launch and modifying kernel settings via root, then reverting on exit.
  • Data Integrity Checks: Before allowing a critical `mount` command, the wrapper could run a `fsck` on the target partition (if unmounted and supported) to ensure filesystem health.

Conclusion

Custom SU wrapper scripts are a powerful, yet often overlooked, tool in the Android modding arsenal. By acting as an intelligent proxy for the `su` binary, they unlock a new dimension of control and customization over your rooted device’s core functionality. Whether for enhanced security logging, automated system tasks, or intricate environment management, mastering these scripts empowers you to tailor your Android experience to an unprecedented degree. Always exercise caution, test thoroughly, and leverage systemless solutions like Magisk to maintain device stability and ease of management.

Android Mobile Specs & Compare Directory

Are you researching mobile hardware properties, processor SoCs, GPU chipsets, or RAM configurations? Access our complete specs catalog to compare up to 5 devices side-by-side!

Compare Devices Specs →
Google AdSense Inline Placement - Content Footer banner