Commit Graph
2230 Commits
Author SHA1 Message Date
topjohnwu a51dc10f88 native: Simplify and deduplicate package lookup
- Expose MagiskD::get_app_id via CXX bridge and reuse it in denylist
  instead of duplicating user collection and package UID lookup in C++.
- Remove redundant manager package name returns, Status enum, and the
  ManagerInfo wrapper struct now that the package name is fixed.

Assisted-by: Gemini 4 Argon
2026-10-22 14:06:48 -07:00
topjohnwu e8e8c3e3f1 Fix HSUM su policy lookup and manager tracking
Normalize system and shared-UID (< 10000) processes to their app ID
when evaluating su policies and uid_granted_root so policies stored by
PolicyDao.normalizeUid match across non-zero users on HSUM devices.

- Normalize eval_uid in build_su_info and uid in uid_granted_root when
  app_id < AID_APP_START.
- Ensure SECURE_DIR exists before writing settings in boot_complete(),
  seed SuMultiuserMode on HSUM, and check isHeadlessSystemUser in
  Info.showSuperUser.
- Normalize UID comparisons in PackageManager.getPackageInfo(uid, pid).
- Simplify ManagerInfo to track a single TrackedFile instead of a
  per-user BTreeMap.
- Skip negative parse_int results in deny collect_users.

Assisted-by: Gemini 4 Argon
2026-10-22 14:06:48 -07:00
topjohnwu c86a8776ce Remove stub embedding from native and scripts
Remove stub.apk and stub.xz extraction, compression,
ramdisk embedding, and daemon auto-installation from native
components (magiskinit, magiskd, scripting), installation
scripts, MagiskInstaller, and build.py.

Assisted-by: Gemini 4 Argon
2026-10-22 14:06:48 -07:00
topjohnwu 5f2faee618 native: Remove custom package and cert validation
Remove support for custom/repackaged manager package names
(su_manager / repackaged_pkg) and secondary certificate verification
(repackaged_cert) from the native daemon and database.

- Remove SuManager from DbEntryKey in CXX bridge and db.rs.
- Remove unused get_db_string and rm_db_string methods from MagiskD.
- Delete check_dyn and check_stub in package.rs.
- Remove repackaged_* fields from ManagerInfo and derive Default.
- Simplify find_apk_path, get_package_uid, and get_manager to target
  APP_PACKAGE_NAME and verify against TRUSTED_CERT.
- Bump SQLite DB_VERSION to 13, drop strings table on migration, and
  remove create_strings from new database initialization.
- Remove obsolete hidden/stub app sections from FAQ documentation.

Assisted-by: Gemini 4 Argon
2026-10-22 14:06:48 -07:00
topjohnwu ea16c8141e Fix package management and user targeting on HSUM
- Use --user current for pm install, adb install, and appops set across
  install_script, adb_pm_install, and test/setup scripts.
- Skip headless user 0 in get_users() on HSUM devices.
- Use --user current in app_notify for non-app UIDs instead of calling
  content call against all users.
- Clear path buffer on each iteration in setup_magisk_env.
- Use --user current for am instrument in app migration tests.

Assisted-by: Gemini 4 Argon
2026-10-22 14:06:48 -07:00
topjohnwu c275a4ea30 Embed trusted certificate in flags.rs
- Extract the signing certificate from keyStore via keytool in
  dump_flags_native() and emit TRUSTED_CERT in flags.rs (or an empty
  slice when keyStore is not configured).
- Replace dynamic certificate extraction from stub.apk in
  preserve_stub_apk() with the static TRUSTED_CERT constant.
- Move get_package_uid() out of MagiskD into a standalone function.

Assisted-by: Gemini 4 Argon
2026-10-22 14:06:48 -07:00
topjohnwu b43a08fdde Bump minSdk to 24 and drop API 23 workarounds
- Bump minSdk to 24 in Setup.kt, APP_PLATFORM to android-24 in
  Application.mk, and update CI AVD matrices and scripts.
- Unify SePatchStrategy::Legacy with SePatchStrategy::SelinuxFs in
  magiskinit to use MOCK_ENFORCE FIFO blocking and remove MOCK_REQPROT.
- Make APP_DATA_DIR a compile-time "/data/user_de" constant and remove
  pre-API 24 /data/user and /data/adb fallbacks.
- Remove Android 6.0 Samsung forkAndSpecialize JNI hook signature.
- Remove pre-API 24 device-protected storage wrappers, Api23Impl in
  LocaleSetting, AndroidManifest.xml stub resource workaround, and
  ServiceCompat/ProcessCompat/InlinedApi workarounds in the app.

Assisted-by: Gemini 4 Argon
2026-10-22 14:06:48 -07:00
leoca 87e72a582e Use DER encoding for AVB1 ECDSA signatures
The AVB 1.0 BootSignature format comes from AOSP's BootSignature.java,
which signs and verifies with Java's SHA256withECDSA family. Those
produce and expect ASN.1 DER encoded (r, s) signatures.

magiskboot wrote and parsed the fixed width r || s form instead. An
image signed by AOSP with an EC key was therefore not recognized by
`magiskboot verify` (nor flagged AVB1_SIGNED by unpack), and an image
signed by `magiskboot sign-avb1` with an EC key was rejected by AOSP's
verifier with "Invalid encoding for signature".

Encode and decode ECDSA signatures as DER. RSA is unchanged.

Assisted-by: Claude Opus 5.5
2026-10-15 00:38:20 +02:00
topjohnwu e8915d9db1 su: remove obsolete access and reauth settings
With reactive su request prompts removed and superuser permissions
granted explicitly ahead of time in the app, the legacy 4-way superuser
access mode (Disabled, Apps only, ADB only, Apps & ADB) and pre-O
reauthentication after upgrade settings are no longer applicable.

ADB shell (com.android.shell) is now an explicit policy entry managed
directly in the Superuser tab, making global access filters redundant
and prone to conflicting state. Furthermore, revoking policy on package
upgrade without reactive prompting silently breaks root for upgraded
apps.

- Remove RootAccess enum and root_access checks from magiskd.
- Remove su access mode and reauthenticate settings from Manager app.
- Drop ACTION_PACKAGE_REPLACED from Receiver and manifests.
- Purge obsolete string resources across all translations.

Assisted-by: Gemini 3.8 Flash
2026-10-09 09:37:15 -07:00
topjohnwu a77198ea60 su: do not notify app when UID has no policy
With reactive su prompting removed, root requests from UIDs without
an existing policy in the database are rejected immediately. Previously,
RootSettings defaulted log and notify to true, causing the daemon to
notify the manager app whenever an unconfigured UID attempted to run
su.

Derive Default for RootSettings so that policy defaults to Deny with
log and notify initialized to false, preventing unwanted notifications
to the app when no database policy exists. Also simplify SuInfo::allow
and SuInfo::deny to leverage Default.

Assisted-by: Gemini 3.8 Flash
2026-10-09 07:16:48 +00:00
topjohnwu 0265698710 Preserve Samsung SignerVer02
Fix #9938, close #10137
2026-10-07 03:18:47 +00:00
topjohnwu cdb02ea12a Several small improvements and bug fixes 2026-10-07 02:58:28 +00:00
topjohnwu 43afdf16a8 Automatically re-sign ChromeOS images on repack
Instead of requiring scripts to detect ChromeOS images and sign them
after repacking, preallocate the vblock and append the kernel blob
trailer while repacking, then generate the vblock after all other
patching is done. The image is padded to its original size after
signing, same as other boot images.

The signer now only takes the kernel payload and returns the vblock,
hashing the kernel blob incrementally. The sign-chromeos action
streams its output to disk instead of building the whole signed
image in memory.

Since ChromeOS images no longer need special handling, unpack no
longer returns 2 for them, and all ChromeOS logic is removed from
the scripts.

Assisted-by: Claude Opus 5.5
2026-10-06 23:36:12 +00:00
topjohnwu da50b5586f Sign ChromeOS boot images with magiskboot
Port the `futility vbutil_kernel --pack` code path used to sign
ChromeOS boot images into magiskboot as a new `sign-chromeos` action.
The kernel keyblock and data key are embedded into the executable, and
all signing parameters previously passed in sign_chromeos are
hardcoded. The output is bit-for-bit identical to the reference tool.

Rename the existing `sign` action to `sign-avb1` to disambiguate.

Remove the prebuilt futility binary and stop shipping the chromeos
assets folder; scripts now call magiskboot directly.

Assisted-by: Claude Opus 5.5
2026-10-06 22:59:48 +00:00
fhgffy 806ecdf8e8 Handle NULL database strings safely
SQLite returns a null pointer for SQL NULL. Passing it to rust::Str
crashes the daemon when a query result contains a NULL column.

Return an empty Rust string for NULL while leaving the raw C++ getter
unchanged, so callers that distinguish NULL can keep doing so.

Fixes: #10131
Assisted-by: GPT-6
2026-10-05 22:06:05 -07:00
topjohnwu 441ac32623 Handle the situation when connect_daemon returns -1
Fix #10117, close #10141
2026-10-06 03:45:05 +00:00
vvb2060 c155d9f0d1 su: add legacy cmd compatibility check 2026-10-05 20:03:11 -07:00
vvb2060 160fb3e40b su: pass all unknown options 2026-10-05 20:03:11 -07:00
topjohnwu 8f0cc199e7 core: resolve user 0 assumptions for HSUM
On Headless System User Mode (HSUM) devices, user 0 is headless while
human users operate under secondary user IDs. Eliminate residual
assumptions in core native components where user 0 was presumed to be
the sole or active manager user:

- In setup_magisk_env, scan all existing users via get_users() to check
  if the app-local binary install directory exists.
- In ensure_manager, check all users before falling back to stub install
  so an already-installed manager on a secondary user is recognized.
- Pass --user all to pm install, pm uninstall, and appops set in package
  management scripts to handle manager lifecycle device-wide.

Assisted-by: Gemini 3.8 Flash
2026-10-05 18:20:32 -07:00
topjohnwu e097945851 su: unify su usage callback to notify action
Consolidate su notification and logging IPC calls into a single notify
action on the native side, passing all logging parameters along with an
explicit "log" boolean key.

On the application side, retain the existing "log" action entry point
for backwards compatibility with older daemons, and update the "notify"
handler to dispatch to either logging or notification based on the
boolean values.

Assisted-by: Gemini 3.8 Flash
2026-10-05 18:20:32 -07:00
topjohnwu 813f9cb9d4 Support Headless System User Mode (HSUM)
On Headless System User Mode (HSUM) devices (e.g. Android Automotive
OS and shared tablets), user 0 is strictly a non-interactive background
system user while human users operate as secondary users (user 10+).

- Check ro.fw.mu.headless_system_user in daemon_entry and store it on
  MagiskD.
- Enforce MultiuserMode::User on HSUM devices and seed the setting in
  magisk.db during post-fs-data, avoiding duplicate override logic.
- For non-app UIDs (< AID_APP_START), scan all discovered users from
  /data/user_de to resolve the manager package/UID and broadcast su
  usage notifications across all users.
- Include system UIDs (< 10000) in PolicyDao.fetchAll() so ADB shell
  (UID 2000) policies can be loaded on secondary users.
- Hide the Multiuser Mode setting in the app on HSUM devices.

Assisted-by: Gemini 3.8 Flash
2026-10-05 18:20:32 -07:00
topjohnwu a1cf051ac7 su: remove legacy am start fallback
Historically, magiskd fell back to `am start` when notifying the app
if `content call` failed. With interactive su prompts removed and
SuRequestActivity slated for removal, this fallback is obsolete.

Rely exclusively on ContentProvider calls for su logging and notify
events, log content call errors directly, and remove Extra::add_intent.

Assisted-by: Gemini 3.8 Flash
2026-10-05 01:38:20 -07:00
topjohnwu 9a101215f1 su: remove interactive su request prompt
With the ability to explicitly grant superuser access in the app,
reactive su prompting and waiting for user response via an interactive
dialog is no longer needed.

- Remove app_request and the associated FIFO / poll waiting logic.
- Change the default SuPolicy and RootSettings from Query to Deny.
- Make SuInfo immutable by removing the internal Mutex<AccessInfo>,
  flattening settings into SuInfo, and refreshing with an updated
  clone on cache hits.
- Remove SuAppContext and convert notification and logging logic into
  private MagiskD methods.

Assisted-by: Gemini 3.8 Flash
2026-10-05 01:38:20 -07:00
vvb2060 9316445516 su: fix -g/-G 2026-10-04 23:12:01 -07:00
topjohnwu 70bf88c383 magiskboot: detect format for XZ BCJ filter
Detect the architecture and file format from input bytes to apply the
proper BCJ pre-filter when compressing with XZ:

- ELF binaries: map e_machine to x86, ARM-Thumb, ARM64, or RISC-V.
- Linux kernels: detect ARM64 raw Image, RISC-V Image, and ARM32 raw
  vmlinux.bin via condition-code density.
- Non-code data: omit BCJ filters to avoid degradation.

Introduce get_encoder_bcj_detection and eliminate the redundant
compress_bytes_kernel and compress_len_kernel helpers.

Assisted-by: Gemini 3.8 Flash
2026-10-04 04:07:03 +00:00
topjohnwu f7a9b39be2 sepolicy: switch to open_memstream
Replace BSD funopen with POSIX open_memstream when dumping the policy
image into memory. Also update the crt0 submodule which implements
open_memstream and fixes duplicate mmap64 definitions on 32-bit targets.

Assisted-by: Gemini 3.8 Flash
2026-10-03 18:27:40 -07:00
topjohnwu a70a7e67b0 Fix host build compatibility with GCC
Fix compilation errors when building host binaries (such as magiskboot)
using GCC on Linux:
- Define _GNU_SOURCE in base and boot build.rs for glibc extensions.
- Add missing <cstdarg>, <cstring>, and <memory> standard headers.
- Provide a fallback definition for __printflike on glibc.
- Implement portable strscpy without relying on BSD strlcpy.
- Add unwrap_ref in bootimg.hpp to allow binding references to packed
  struct members under GCC.
- Remove cxx_impl_annotations in codegen.rs to prevent always_inline
  from being emitted on header declarations without function bodies.

Assisted-by: Gemini 3.8 Flash
2026-10-03 06:35:05 +00:00
topjohnwu 66bcdaf4e0 magiskboot: support building on host
Allow magiskboot to be built directly on host platforms (macOS and
Linux) using Cargo:
- Add a binary target to boot module with a no_main entry point that
  directly reuses the C main CLI implementation.
- Compile native C and C++ sources (base, boot, cxx, and lz4) via cc in
  base and boot build.rs when target_os is not Android.
- Platform gate Linux-specific functionality (SELinux xattrs, mount,
  namespaces) in base on Linux and Android, and provide macOS fallback
  for xsendfile.
- Move MountInfo and mount parsing from files to mount module.
- Scope Android-specific LTO rustflags in config.toml to Android
  targets.
- Ensure build.py compiles Rust modules as static libraries (--lib).

Assisted-by: Gemini 3.8 Flash
2026-10-02 17:17:48 -07:00
topjohnwu 33d09a2aff Expose xpipe2 as symbol 2026-10-02 17:17:48 -07:00
topjohnwu 32ee775026 Cleanup base.cpp 2026-10-02 17:17:48 -07:00
topjohnwu 8348d6e39c base: eliminate /proc/self/fd path resolution
Remove reliance on /proc/self/fd symlink resolution across base and core
components:
- Add top-level pre_order_walk and post_order_walk that track entry
  paths via an internal buffer, and unify Directory walk methods to
  support path-tracking and pathless traversals without extra overhead.
- Add DirEntry::get_stat using fstatat(AT_SYMLINK_NOFOLLOW) directly on
  directory file descriptors.
- Update Directory::copy_into and link_into to operate directly on file
  descriptors with fd_get_attr/fd_set_attr, passing paths only for
  symlink attribute updates.
- Refactor find_apk_path and restore_tmpcon to use pre_order_walk, and
  update get_app_no_list to use DirEntry::get_stat.
- Remove DirEntry::resolve_path, Directory::path_at,
  Directory::resolve_path, and fd_path.
- Replace remaining consumers of xrealpath and canonical_path (in su
  and magiskinit) with standard realpath or partition matching, allowing
  removal of Utf8CStr::realpath and its C FFI exports.

Assisted-by: Gemini 3.8 Flash
2026-10-02 17:17:48 -07:00
topjohnwu 0e228db61f Reduce more Linux specific code in base 2026-10-02 17:17:48 -07:00
topjohnwu b76d674a60 Move daemon utilities from base to core
Move utilities that are exclusively used by the daemon (core module)
from base to core:
- fork_dont_care, fork_no_orphan, new_daemon_thread, init_argv0,
  set_nice_name, and switch_mnt_ns into utils.cpp
- exec_command* functions and exec_t into scripting.cpp as static
  functions, as scripting is their sole consumer

Also remove the unused exec_command_sync overload.

Assisted-by: Gemini 3.8 Flash
2026-10-02 17:17:48 -07:00
topjohnwu 93708e5e73 Use nix Errno 2026-10-02 17:17:48 -07:00
LoveSy 07390a7860 Revert "Update AVB hash header image_size to match unpacked original_image_size."
This reverts commit d9a9b02c27.
2026-09-23 18:57:19 -07:00
topjohnwu 89d3100ffc Update cargo dependencies 2026-09-20 02:21:59 -07:00
topjohnwu da320823ac magiskboot: enable BCJ filter for XZ compression
Enable the architecture-specific BCJ pre-filter when creating XzWriter
for supported ABIs. For ARM32 kernel compression, use the standard ARM
filter rather than Thumb-2.

Assisted-by: Gemini 3.8 Flash
2026-09-20 02:21:59 -07:00
topjohnwu 9e8ff0d1bd Update xz-embedded to upstream submodule
Add https://github.com/tukaani-project/xz-embedded as a submodule
pinned to tag v2024-12-30, replacing previously vendored sources.
Keep customized userspace configuration in external/xz_config with
architecture-specific BCJ filters and CRC64 support.

Assisted-by: Gemini 3.8 Flash
2026-09-20 02:21:59 -07:00
topjohnwu 6d391dd5b1 magiskboot: handle decompression errors in unpack
Previously, decompress_bytes dropped the LoggedResult from decoding,
returning void. In bootimg.cpp, unpack and split_image_dtb never checked
whether decompression succeeded, leaving empty 0-byte output files and
returning RETURN_OK (0).

Return a boolean status from decompress_bytes and check it during unpack
and split_image_dtb. On decompression failure, remove any incomplete
output files and return RETURN_ERROR (1).

Assisted-by: Gemini 3.8 Flash
2026-09-18 16:50:34 -07:00
topjohnwu 887a97822b magiskboot: search compressed formats in zImage
When locating the compressed piggy payload in a zImage, check only
formats where fmt.is_compressed() to avoid false positives on container
or header formats (such as DTB or Android boot magic).

Additionally, prioritize 4-byte aligned offsets since ARM kernel linker
scripts align .piggydata to 4 bytes, falling back to an unaligned scan
only if no candidate is found.

Assisted-by: Gemini 3.8 Flash
2026-09-18 16:50:34 -07:00
topjohnwu 8376f7b27c magiskboot: validate XZ header CRC in check_fmt
XZ decompressor stubs in 32-bit ARM Linux zImage (lib/decompress_unxz.c)
include the HEADER_MAGIC string literal "\3757zXZ" in .rodata, which
appears before the compressed payload. check_fmt previously matched
only the first 5 bytes, falsely identifying the .rodata string literal
as an XZ payload.

Validate the 12-byte XZ stream header by verifying the 6-byte magic,
stream flags, and IEEE 802.3 CRC32 of the stream flags. In addition,
harden GZIP, BZIP2, and LZOP checks with stricter header validation
to prevent false positives when scanning raw binaries.

Assisted-by: Gemini 3.8 Flash
2026-09-18 16:50:34 -07:00
Wang Han a11ef9a4de Fix su daemon exec behavior after rust migration
Use fork_dont_care() to perform async exec and unblock all signals.
2026-09-17 22:20:42 -07:00
topjohnwu 584ba3227e Update cargo dependencies 2026-09-04 09:44:49 -07:00
Wang Han 6833e56398 Don't kill webview zygote on denylist change
It won't restart and make webview unusable.
2026-08-30 20:52:34 +00:00
Wang Han b2d86c79c2 Add webview zygote as umount target
https://github.com/tiann/KernelSU/commit/4521784328352c54334beb29e05c74360b60d7cb
2026-08-30 02:59:46 -07:00
Wang Han 4145e5205a Bump MIN_NON_EMPTY_DTB_SIZE to 0x84 2026-08-30 05:03:41 +00:00
topjohnwu f38e0c8bc6 su: Enable logging and notify by default
When a UID makes a root request for the first time, no row exists in
the policies table. Previously, RootSettings derived Default, which
initialized log and notify to false. As a result, connect_app() skipped
calling app_log() or app_notify() immediately after user approval on
the initial su request.

Explicitly implement Default for RootSettings with log and notify set
to true by default.

Assisted-by: Gemini 3.7 Flash
2026-08-30 00:03:52 +00:00
xAstroBoy 8903cf7f22 zygisk: make built-in Zygisk work on Meta Quest (lazy per-trust partition zygotes)
Meta Quest (Horizon OS) does not start the zygote the normal way: ro.zygote=
zygote64_stub32 launches /system/bin/stub_zygote, which forks a separate
app_process64 zygote PER security partition (system/trusted vs untrusted-app),
driven by hzos_security_zygote_partitioning_policy. The untrusted-app partition
zygote -- the one that forks 3rd-party apps and the Magisk manager -- is spawned
LAZILY, after boot-complete.

magiskd sets ro.dalvik.vm.native.bridge=libzygisk.so during boot but clears it
again at boot-complete (ZygiskState::reset). On a normal device every zygote has
already started by then, so clearing it is harmless. On Quest the untrusted-app
partition zygote reads the (now cleared) property when it finally execve's
app_process64, never loads libzygisk.so, so 3rd-party apps + the Magisk manager
are never injected -> "Zygisk: N/A".

Fix (daemon.rs): on the boot-complete reset(restore=true) path, reset the crash
counter but KEEP native.bridge set (set_prop) instead of clearing it
(restore_prop); only the >3-crash rollback path still clears. The lazily-spawned
partition zygotes then load the loader when they start.

Also (hook.cpp), robustness fixes the loader needs on this device:
 - Wrap hook_zygote_jni()'s JNI locals in PushLocalFrame(64)/PopLocalFrame so
   leaking locals can't trip ART's "non-empty local reference table" abort, and
   bail if GetEnv returns no env.
 - Make the strdup(ZygoteInit) trigger a substring match + add an idempotency
   guard so the zygote hooks install exactly once per process.

Verified on Quest 3 (Android 14): system_server + every app fork is intercepted
and LSPosed loads end-to-end.
2026-08-27 05:38:45 +00:00
Wang Han 5a28d2fcfc Backup original sepolicy db for LD_PRELOAD strategy 2026-08-27 05:38:01 +00:00
topjohnwu 4623f546e3 Convert subproject AGENTS.md into skills 2026-08-26 05:42:55 +00:00