30 Commits

Author SHA1 Message Date
snake-4
72f96df644 Bumped version to 2.1.0 2024-04-24 08:29:08 +02:00
snake-4
e03060eb22 Added Zygisk hide for 27.0 and renamed unmount.cpp 2024-04-24 07:45:04 +02:00
snake-4
71eee6bf92 Added ELFIO submodule 2024-04-24 07:01:50 +02:00
snake-4
29d4adca9e Changes to build system 2024-04-22 01:57:38 +02:00
snake-4
c0246483b0 Fixed companion FD for child zygotes 2024-04-17 00:27:40 +02:00
snake-4
e22e81d792 Updated AGP to 8.3.2...
and misc changes.
2024-04-16 23:16:21 +02:00
snake-4
5e8a2c4631 Added setresuid hook for older Android versions 2024-04-16 22:43:03 +02:00
snake-4
a7701e8b11 Updated logs and remount logic 2024-04-16 21:08:45 +02:00
snake-4
f200aa4561 Added root companion and logging macros 2024-04-16 21:08:10 +02:00
snake-4
2962997439 Moved unmount to unshare hook
This might break older Android versions. Not sure.
2024-04-16 21:07:47 +02:00
snake-4
6a61f6a4b6 Renamed some functions 2024-04-14 18:37:38 +02:00
snake-4
6e333581fb Added remount function and changed bind mount...
prefix.
2024-04-14 16:23:38 +02:00
snake-4
ac910f0ebe Unhook unshare at postAppSpecialize 2024-04-14 16:21:52 +02:00
snake-4
df3e492391 Update update.json 2024-04-12 12:50:47 +02:00
snake-4
7ec3214927 Bumped version to 2.0.4 2024-04-12 12:43:42 +02:00
snake-4
c797376230 Update main.cpp 2024-04-10 00:52:12 +02:00
snake-4
33a9ff93f4 Updated ci.yml and fixed build 2024-04-09 23:07:04 +02:00
snake-4
6f4d78b0fc Added maps parser and fixed child zygote namespaces 2024-04-09 22:35:40 +02:00
snake-4
08547864cd Added missing header guards, bumped to C++20 2024-04-09 20:32:28 +02:00
snake-4
d59ac2bf26 Updated AGP and compileSdkVersion 2024-04-09 05:34:27 +02:00
snake-4
52e5771205 Updated AGP to 8.3.0 2024-04-06 20:17:39 +02:00
snake-4
ce278b37f7 Update update.json 2024-04-01 05:10:13 +02:00
snake-4
fe05fbd621 Bumped version to v2.0.3 2024-04-01 05:05:17 +02:00
snake-4
83f2880922 Added mountinfo parser and bind mount hiding
closes #3
2024-04-01 04:58:18 +02:00
snake-4
112c4027fe Update update.json 2024-04-01 02:02:14 +02:00
snake-4
aa9a8a04e3 Bumped version to v2.0.2 2024-04-01 01:58:09 +02:00
snake-4
670767a82b Added exception for hosts bind mount 2024-04-01 01:33:12 +02:00
snake-4
7200b77043 Fixed module template copy task during build
Fixes Magisk compatibility.
2024-04-01 01:23:58 +02:00
snake-4
a07e62fcd7 Create update.json 2024-03-31 23:20:22 +02:00
snake-4
0ee57d586f Added updateJson in module.prop, bumped to v2.0.1 2024-03-31 23:15:32 +02:00
27 changed files with 673 additions and 211 deletions

View File

@@ -1,28 +1,24 @@
name: CI
on:
workflow_dispatch:
push:
branches: [ main ]
tags: [ v* ]
pull_request:
merge_group:
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
submodules: "recursive"
fetch-depth: 0
- name: Setup Java
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
distribution: "temurin"
java-version: "17"
java-version: 17
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v3
- name: Build with Gradle
run: |

3
.gitmodules vendored
View File

@@ -1,3 +1,6 @@
[submodule "libcxx"]
path = module/jni/libcxx
url = https://github.com/topjohnwu/libcxx.git
[submodule "module/jni/elfio"]
path = module/jni/elfio
url = https://github.com/serge1/ELFIO.git

View File

@@ -1,7 +1,7 @@
<h3 align="center">Zygisk Assistant</h3>
<p align="center">
A Zygisk module that hides root by unmounting suspicious mounts in user-mode.
A Zygisk module that aims to hide the existence root and Zygisk.
<br />
<br />
<a href="https://github.com/snake-4/Zygisk-Assistant/issues">Report Bug</a>
@@ -16,7 +16,18 @@
<!-- ABOUT THE PROJECT -->
## About The Project
This module creates a new transparent namespace for each application in preAppSpecialize and unmounts common root mounts.
Using the **release** build is recommended over the debug build. Only use debug builds if you are going to make a bug report.
### KernelSU & APatch users:
1. Install ZygiskNext.
1. Make sure the unmount setting is enabled for the target app in the KernelSU/APatch Manager.
1. Disable `Enforce DenyList` in ZygiskNext settings if there is one.
### Magisk users:
1. Update your Magisk to 27.0 or newer for better hiding capabilities. (optional)
1. Turn on Zygisk in Magisk settings.
1. Turn off `Enforce DenyList` in Magisk settings.
1. Add the target app to the deny list unless you're using a Magisk fork with a white list instead.
<!-- CONTRIBUTING -->

View File

@@ -1,20 +1,19 @@
import java.io.ByteArrayOutputStream
plugins {
alias(libs.plugins.agp.lib) apply false
id("com.android.library") version "8.3.2" apply false
}
val commitHash: String by extra({
val commitHash: String by extra {
val stdout = ByteArrayOutputStream()
rootProject.exec {
commandLine("git", "rev-parse", "--short", "HEAD")
standardOutput = stdout
}
stdout.toString().trim()
})
}
val moduleId by extra("zygisk-assistant")
val moduleName by extra("Zygisk Assistant")
val verName by extra("v2.0.0")
val verCode by extra(200)
val abiList by extra(listOf("armeabi-v7a","arm64-v8a","x86","x86_64"))
val verName by extra("v2.1.0")
val verCode by extra(210)

View File

@@ -1,5 +0,0 @@
[versions]
agp = "8.2.0"
[plugins]
agp-lib = { id = "com.android.library", version.ref = "agp" }

View File

@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME

View File

@@ -1,7 +1,7 @@
import android.databinding.tool.ext.capitalizeUS
plugins {
alias(libs.plugins.agp.lib)
id("com.android.library")
}
val moduleId: String by rootProject.extra
@@ -16,9 +16,6 @@ android {
compileSdkVersion = "android-31"
defaultConfig {
minSdk = 21
ndk {
abiFilters.addAll(abiList)
}
externalNativeBuild {
ndkBuild {
arguments("-j${Runtime.getRuntime().availableProcessors()}")
@@ -37,7 +34,7 @@ androidComponents.onVariants { variant ->
val variantCapped = variant.name.capitalizeUS()
val buildTypeLowered = variant.buildType?.lowercase()
val libOutDir = layout.buildDirectory.dir("intermediates/stripped_native_libs/$variantLowered/out/lib").get()
val libOutDir = layout.buildDirectory.dir("intermediates/stripped_native_libs/$variantLowered/strip${variantCapped}DebugSymbols/out/lib").get()
val moduleDir = layout.buildDirectory.dir("outputs/module/$variantLowered").get()
val zipOutDir = layout.buildDirectory.dir("outputs/release").get()
val zipFileName = "$moduleName-$verName-$commitHash-$buildTypeLowered.zip".replace(' ', '-')
@@ -55,6 +52,9 @@ androidComponents.onVariants { variant ->
"versionCode" to verCode
)
}
from("$projectDir/template") {
exclude("module.prop")
}
from(libOutDir) {
into("zygisk")
}

View File

@@ -1,9 +1,9 @@
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include $(LOCAL_PATH)/elfio
LOCAL_MODULE := zygisk
LOCAL_SRC_FILES := mount_parser.cpp unmount.cpp main.cpp
LOCAL_SRC_FILES := utils.cpp map_parser.cpp mount_parser.cpp mountinfo_parser.cpp modules.cpp main.cpp
LOCAL_STATIC_LIBRARIES := libcxx
LOCAL_LDLIBS := -llog
include $(BUILD_SHARED_LIBRARY)

View File

@@ -1,4 +1,4 @@
APP_ABI := armeabi-v7a arm64-v8a x86 x86_64
APP_CPPFLAGS := -std=c++14 -fno-exceptions -fno-rtti -fvisibility=hidden -fvisibility-inlines-hidden
APP_CPPFLAGS := -std=c++20 -fno-exceptions -fno-rtti -fvisibility=hidden -fvisibility-inlines-hidden
APP_STL := none
APP_PLATFORM := android-31

1
module/jni/elfio Submodule

Submodule module/jni/elfio added at 45af83bc67

View File

@@ -1,15 +1,16 @@
#pragma once
#include <android/log.h>
#include <string.h>
#include <errno.h>
#include <cstring>
#include <cerrno>
#include <cinttypes>
#ifndef NDEBUG
static constexpr auto TAG = "ZygiskAssistant/JNI";
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
#else
#define LOGD(...)
#define LOGI(...)
#define LOGW(...)
#define LOGE(...)
#endif

View File

@@ -0,0 +1,28 @@
#pragma once
#include <sstream>
#include <string>
#include <vector>
#include <sys/types.h>
class map_entry_t
{
public:
map_entry_t(uintptr_t address_start, uintptr_t address_end, uintptr_t offset,
const std::string &perms, const std::string &pathname, dev_t device, ino_t inode);
uintptr_t getAddressStart() const;
uintptr_t getAddressEnd() const;
const std::string &getPerms() const;
uintptr_t getOffset() const;
dev_t getDevice() const;
ino_t getInode() const;
const std::string &getPathname() const;
private:
uintptr_t address_start, address_end, offset;
std::string perms, pathname;
dev_t device;
ino_t inode;
};
std::vector<map_entry_t> parseMapsFromPath(const char *path);

View File

@@ -0,0 +1,5 @@
#pragma once
void doUnmount();
void doRemount();
void doHideZygisk();

View File

@@ -1,3 +1,4 @@
#pragma once
#include <string>
#include <vector>
#include <unordered_map>
@@ -16,14 +17,10 @@ public:
int getPassNumber() const;
private:
void parseMountOptions(const std::string &input);
std::string fsname;
std::string dir;
std::string type;
std::string fsname, dir, type;
std::unordered_map<std::string, std::string> opts_map;
int freq;
int passno;
int freq, passno;
};
std::vector<mount_entry_t> parseMountsFromPath(const char *path);
std::unordered_map<std::string, std::string> parseMountOptions(const std::string &input);

View File

@@ -0,0 +1,33 @@
#pragma once
#include <string>
#include <vector>
#include <unordered_map>
class mountinfo_entry_t
{
public:
mountinfo_entry_t(int mount_id, int parent_id, int major, int minor,
const std::string &root, const std::string &mount_point,
const std::string &mount_options, const std::string &optional_fields,
const std::string &filesystem_type, const std::string &mount_source,
const std::string &super_options);
int getMountId() const;
int getParentId() const;
int getMajor() const;
int getMinor() const;
const std::string &getRoot() const;
const std::string &getMountPoint() const;
const std::unordered_map<std::string, std::string> &getMountOptions() const;
const std::string &getOptionalFields() const;
const std::string &getFilesystemType() const;
const std::string &getMountSource() const;
const std::unordered_map<std::string, std::string> &getSuperOptions() const;
private:
int mount_id, parent_id, major, minor;
std::string root, mount_point, optional_fields, filesystem_type, mount_source;
std::unordered_map<std::string, std::string> mount_options, super_options;
};
std::vector<mountinfo_entry_t> parseMountinfosFromPath(const char *path);

View File

@@ -0,0 +1,20 @@
#pragma once
#include <string>
#include <errno.h>
#include "logging.hpp"
#include "zygisk.hpp"
#define DCL_HOOK_FUNC(ret, func, ...) \
ret (*old_##func)(__VA_ARGS__) = nullptr; \
ret new_##func(__VA_ARGS__)
#define ASSERT_LOG(tag, expr) if(!(expr)) { \
LOGE("%s:%d Assertion %s failed. %d:%s", tag, __LINE__, #expr, errno, std::strerror(errno)); }
#define ASSERT_EXIT(tag, expr, ret) if(!(expr)) { \
LOGE("%s:%d Assertion %s failed. %d:%s", tag, __LINE__, #expr, errno, std::strerror(errno)); \
ret; }
bool switchMountNS(int pid);
int isUserAppUID(int uid);
bool hookPLTByName(zygisk::Api *api, const std::string &libName, const std::string &symbolName, void *hookFunc, void **origFunc);

View File

@@ -1,26 +1,56 @@
#include <unistd.h>
#include <sched.h>
#include <sys/mount.h>
#include <cstdint>
#include <functional>
#include "zygisk.hpp"
#include "logging.hpp"
#include "android_filesystem_config.h"
#include "utils.hpp"
#include "modules.hpp"
using zygisk::Api;
using zygisk::AppSpecializeArgs;
using zygisk::ServerSpecializeArgs;
void do_unmount();
static std::function<void()> callbackFunction = []() {};
static int shouldSkipUid(int uid)
/*
* [What's the purpose of this hook?]
* Calling unshare twice invalidates existing FD links, which fails Zygote sanity checks.
* So we prevent further namespaces by hooking unshare.
*
* [Doesn't Android already call unshare?]
* Whether there's going to be an unshare or not changes with each major Android version
* so we unconditionally unshare in preAppSpecialize.
* > Android 5: Conditionally unshares
* > Android 6: Always unshares
* > Android 7-11: Conditionally unshares
* > Android 12-14: Always unshares
*/
DCL_HOOK_FUNC(static int, unshare, int flags)
{
int appid = uid % AID_USER_OFFSET;
if (appid >= AID_APP_START && appid <= AID_APP_END)
return false;
if (appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END)
return false;
return true;
callbackFunction();
// Do not allow CLONE_NEWNS.
flags &= ~(CLONE_NEWNS);
if (!flags)
{
// If CLONE_NEWNS was the only flag, skip the call.
errno = 0;
return 0;
}
return old_unshare(flags);
}
/*
* The reason why we hook setresuid is because so far it has been unconditionally called
* and we still have CAP_SYS_ADMIN during this call.
*/
DCL_HOOK_FUNC(static int, setresuid, uid_t ruid, uid_t euid, uid_t suid)
{
callbackFunction();
return old_setresuid(ruid, euid, suid);
}
class ZygiskModule : public zygisk::ModuleBase
@@ -39,46 +69,60 @@ public:
uint32_t flags = api->getFlags();
bool isRoot = (flags & zygisk::StateFlag::PROCESS_GRANTED_ROOT) != 0;
bool isOnDenylist = (flags & zygisk::StateFlag::PROCESS_ON_DENYLIST) != 0;
if (isRoot || !isOnDenylist || shouldSkipUid(args->uid))
bool isChildZygote = args->is_child_zygote != NULL && *args->is_child_zygote;
if (isRoot || !isOnDenylist || !isUserAppUID(args->uid))
{
LOGD("Skipping pid=%d uid=%d", getpid(), args->uid);
LOGD("Skipping ppid=%d uid=%d isChildZygote=%d", getppid(), args->uid, isChildZygote);
return;
}
LOGD("Unmounting in preAppSpecialize for pid=%d uid=%d", getpid(), args->uid);
LOGD("Processing ppid=%d uid=%d isChildZygote=%d", getppid(), args->uid, isChildZygote);
/*
* Create only one namespace per zygote, child Zygotes will inherit it
* But then again, why won't they also inherit the unmounts of the parent?
* Either way, unshare in child Zygote will crash at the open FD sanity check.
* Read the comment above unshare hook.
*/
if (!*args->is_child_zygote)
ASSERT_EXIT("preAppSpecialize", unshare(CLONE_NEWNS) != -1, return);
/*
* Mount the app mount namespace's root as MS_SLAVE, so every mount/umount from
* Zygote shared pre-specialization namespace is propagated to this one.
*/
ASSERT_EXIT("preAppSpecialize", mount("rootfs", "/", NULL, (MS_SLAVE | MS_REC), NULL) != -1, return);
ASSERT_EXIT("preAppSpecialize", hookPLTByName("libandroid_runtime.so", "unshare", new_unshare, &old_unshare), return);
ASSERT_EXIT("preAppSpecialize", hookPLTByName("libandroid_runtime.so", "setresuid", new_setresuid, &old_setresuid), return);
int companionFd = -1;
ASSERT_LOG("preAppSpecialize", (companionFd = api->connectCompanion()) != -1);
ASSERT_LOG("preAppSpecialize", companionFd != -1 && api->exemptFd(companionFd));
callbackFunction = [fd = companionFd]()
{
LOGD("Creating new mount namespace for parent pid=%d uid=%d", getpid(), args->uid);
/*
* preAppSpecialize is before ensureInAppMountNamespace.
* postAppSpecialize is after seccomp setup.
* So we unshare here to create a pseudo app mount namespace
*/
if (unshare(CLONE_NEWNS) == -1)
bool result = false;
if (fd != -1)
{
LOGE("unshare(CLONE_NEWNS) returned -1: %d (%s)", errno, strerror(errno));
// Don't unmount anything in global namespace
return;
do
{
pid_t pid = getpid();
ASSERT_EXIT("invokeZygiskCompanion", write(fd, &pid, sizeof(pid)) == sizeof(pid), break);
ASSERT_EXIT("invokeZygiskCompanion", read(fd, &result, sizeof(result)) == sizeof(result), break);
} while (false);
close(fd);
}
/*
* Mount the pseudo app mount namespace's root as MS_SLAVE, so every mount/umount from
* Zygote shared pre-specialization mountspace is propagated to this one.
*/
if (mount("rootfs", "/", NULL, (MS_SLAVE | MS_REC), NULL) == -1)
if (result)
LOGD("Invoking the companion was successful.");
else
{
LOGE("mount(\"rootfs\", \"/\", NULL, (MS_SLAVE | MS_REC), NULL) returned -1");
LOGW("Invoking the companion failed. Performing operations in Zygote context!");
doUnmount();
doRemount();
}
}
do_unmount();
doHideZygisk();
// Call only once per process.
callbackFunction = []() {};
};
}
void preServerSpecialize(ServerSpecializeArgs *args) override
@@ -86,9 +130,43 @@ public:
api->setOption(zygisk::Option::DLCLOSE_MODULE_LIBRARY);
}
void postAppSpecialize(const AppSpecializeArgs *args) override
{
if (old_unshare != nullptr)
ASSERT_LOG("postAppSpecialize", hookPLTByName("libandroid_runtime.so", "unshare", old_unshare));
if (old_setresuid != nullptr)
ASSERT_LOG("postAppSpecialize", hookPLTByName("libandroid_runtime.so", "setresuid", old_setresuid));
}
template <typename T>
bool hookPLTByName(const std::string &libName, const std::string &symbolName, T *hookFunction, T **originalFunction = nullptr)
{
return ::hookPLTByName(api, libName, symbolName, (void *)hookFunction, (void **)originalFunction) && api->pltHookCommit();
}
private:
Api *api;
JNIEnv *env;
};
void zygisk_companion_handler(int fd)
{
bool result = [&]() -> bool
{
pid_t pid;
ASSERT_EXIT("zygisk_companion_handler", read(fd, &pid, sizeof(pid)) == sizeof(pid), return false);
ASSERT_EXIT("zygisk_companion_handler", unshare(CLONE_NEWNS) != -1, return false);
ASSERT_EXIT("zygisk_companion_handler", switchMountNS(pid), return false);
LOGD("zygisk_companion_handler processing namespace of pid=%d", pid);
doUnmount();
doRemount();
return true;
}();
ASSERT_LOG("zygisk_companion_handler", write(fd, &result, sizeof(result)) == sizeof(result));
}
REGISTER_ZYGISK_MODULE(ZygiskModule)
REGISTER_ZYGISK_COMPANION(zygisk_companion_handler)

59
module/jni/map_parser.cpp Normal file
View File

@@ -0,0 +1,59 @@
#include <string>
#include <sstream>
#include <fstream>
#include <vector>
#include <sys/sysmacros.h> // For makedev
#include "map_parser.hpp"
#include "logging.hpp"
map_entry_t::map_entry_t(uintptr_t address_start, uintptr_t address_end, uintptr_t offset, const std::string &perms, const std::string &pathname, dev_t device, ino_t inode)
: address_start(address_start), address_end(address_end), perms(perms),
offset(offset), device(device), inode(inode), pathname(pathname) {}
uintptr_t map_entry_t::getAddressStart() const { return address_start; }
uintptr_t map_entry_t::getAddressEnd() const { return address_end; }
const std::string &map_entry_t::getPerms() const { return perms; }
uintptr_t map_entry_t::getOffset() const { return offset; }
dev_t map_entry_t::getDevice() const { return device; }
ino_t map_entry_t::getInode() const { return inode; }
const std::string &map_entry_t::getPathname() const { return pathname; }
std::vector<map_entry_t> parseMapsFromPath(const char *path)
{
std::vector<map_entry_t> ret;
std::ifstream ifs(path, std::ifstream::in);
if (!ifs)
{
LOGE("parseMapsFromPath could not open file \"%s\"", path);
return ret;
}
for (std::string line; std::getline(ifs, line);)
{
std::istringstream iss(line);
uintptr_t address_start, address_end, offset;
std::string perms;
std::string pathname;
ino_t inode;
int dev_major, dev_minor;
char dummy_char;
iss >> std::hex >> address_start >> dummy_char >> address_end >> perms >> offset >> dev_major >> dummy_char >> dev_minor >> std::dec >> inode;
if (iss.fail())
{
LOGE("parseMapsFromPath failed to parse line: %s", line.c_str());
continue;
}
// This operation can fail, it doesn't matter as it's an optional field.
std::getline(iss >> std::ws, pathname);
ret.emplace_back(map_entry_t(address_start, address_end, offset, perms, pathname, makedev(dev_major, dev_minor), inode));
}
return ret;
}

178
module/jni/modules.cpp Normal file
View File

@@ -0,0 +1,178 @@
#include <string>
#include <vector>
#include <set>
#include <unordered_map>
#include <cstdint>
#include <sys/mount.h>
#include <elfio/elfio.hpp>
#include "zygisk.hpp"
#include "logging.hpp"
#include "map_parser.hpp"
#include "mount_parser.hpp"
#include "mountinfo_parser.hpp"
#include "utils.hpp"
static const std::set<std::string> fsname_list = {"KSU", "APatch", "magisk", "worker"};
static const std::unordered_map<std::string, int> mount_flags_procfs = {
{"nosuid", MS_NOSUID},
{"nodev", MS_NODEV},
{"noexec", MS_NOEXEC},
{"noatime", MS_NOATIME},
{"nodiratime", MS_NODIRATIME},
{"relatime", MS_RELATIME},
{"nosymfollow", MS_NOSYMFOLLOW}};
static bool shouldUnmount(const mountinfo_entry_t &mount_info)
{
const auto &root = mount_info.getRoot();
// Unmount all module bind mounts
return root.starts_with("/adb/");
}
static bool shouldUnmount(const mount_entry_t &mount)
{
const auto &mountPoint = mount.getMountPoint();
const auto &type = mount.getType();
const auto &options = mount.getOptions();
// Unmount everything mounted to /data/adb
if (mountPoint.rfind("/data/adb", 0) == 0)
return true;
// Unmount all module overlayfs and tmpfs
if ((type == "overlay" || type == "tmpfs") && fsname_list.contains(mount.getFsName()))
return true;
// Unmount all overlayfs with lowerdir/upperdir/workdir starting with /data/adb
if (type == "overlay")
{
if (options.contains("lowerdir") && options.at("lowerdir").starts_with("/data/adb"))
return true;
if (options.contains("upperdir") && options.at("upperdir").starts_with("/data/adb"))
return true;
if (options.contains("workdir") && options.at("workdir").starts_with("/data/adb"))
return true;
}
return false;
}
void doUnmount()
{
std::vector<std::string> mountPoints;
// Check mounts first
for (auto &mount : parseMountsFromPath("/proc/self/mounts"))
{
if (shouldUnmount(mount))
{
mountPoints.push_back(mount.getMountPoint());
}
}
// Check mountinfos so that we can find bind mounts as well
for (auto &mount_info : parseMountinfosFromPath("/proc/self/mountinfo"))
{
if (shouldUnmount(mount_info))
{
mountPoints.push_back(mount_info.getMountPoint());
}
}
// Sort by string lengths, descending
std::sort(mountPoints.begin(), mountPoints.end(), [](const auto &lhs, const auto &rhs)
{ return lhs.size() > rhs.size(); });
for (const auto &mountPoint : mountPoints)
{
if (umount2(mountPoint.c_str(), MNT_DETACH) == 0)
{
LOGD("umount2(\"%s\", MNT_DETACH) returned 0", mountPoint.c_str());
}
else
{
LOGW("umount2(\"%s\", MNT_DETACH) returned -1: %d (%s)", mountPoint.c_str(), errno, strerror(errno));
}
}
}
void doRemount()
{
std::vector<mount_entry_t> mounts = parseMountsFromPath("/proc/self/mounts");
auto data_mount_it = std::find_if(mounts.begin(), mounts.end(), [](const mount_entry_t &mount)
{ return mount.getMountPoint() == "/data"; });
if (data_mount_it != mounts.end())
{
const auto &options = data_mount_it->getOptions();
// If errors=remount-ro, remount it with errors=continue
if (options.contains("errors") && options.at("errors") == "remount-ro")
{
unsigned long flags = MS_REMOUNT;
for (const auto &flagName : mount_flags_procfs)
{
if (options.contains(flagName.first))
flags |= flagName.second;
}
if (mount(NULL, "/data", NULL, flags, "errors=continue") == 0)
{
LOGD("mount(NULL, \"/data\", NULL, 0x%lx, \"errors=continue\") returned 0", flags);
}
else
{
LOGW("mount(NULL, \"/data\", NULL, 0x%lx, \"errors=continue\") returned -1: %d (%s)", flags, errno, strerror(errno));
}
}
}
}
/*
* Is it guaranteed to work? No.
* At least it has lots of error checking so if something goes wrong
* the state should remain relatively safe.
*/
void doHideZygisk()
{
using namespace ELFIO;
elfio reader;
std::string filePath;
uintptr_t startAddress = 0, bssAddress = 0;
for (const auto &map : parseMapsFromPath("/proc/self/maps"))
{
if (map.getPathname().ends_with("/libnativebridge.so") && map.getPerms() == "r--p")
{
// First ro page should be the ELF header
filePath = map.getPathname();
startAddress = map.getAddressStart();
break;
}
}
ASSERT_EXIT("doHideZygisk", startAddress != 0, return);
ASSERT_EXIT("doHideZygisk", reader.load(filePath), return);
size_t bssSize = 0;
for (const auto &sec : reader.sections)
{
if (sec->get_name() == ".bss")
{
bssAddress = startAddress + sec->get_address();
bssSize = static_cast<size_t>(sec->get_size());
break;
}
}
ASSERT_EXIT("doHideZygisk", bssAddress != 0, return);
LOGD("Found .bss for \"%s\" at 0x%" PRIxPTR " sized %" PRIuPTR " bytes.", filePath.c_str(), bssAddress, bssSize);
uint8_t *pHadError = reinterpret_cast<uint8_t *>(memchr(reinterpret_cast<void *>(bssAddress), 0x01, bssSize));
ASSERT_EXIT("doHideZygisk", pHadError != nullptr, return);
*pHadError = 0;
}

View File

@@ -7,70 +7,27 @@
#include "mount_parser.hpp"
#include "logging.hpp"
#include "utils.hpp"
mount_entry_t::mount_entry_t(::mntent *entry)
: fsname(entry->mnt_fsname), dir(entry->mnt_dir), type(entry->mnt_type), freq(entry->mnt_freq), passno(entry->mnt_passno)
{
parseMountOptions(entry->mnt_opts);
opts_map = parseMountOptions(entry->mnt_opts);
}
const std::string &mount_entry_t::getFsName() const
{
return fsname;
}
const std::string &mount_entry_t::getMountPoint() const
{
return dir;
}
const std::string &mount_entry_t::getType() const
{
return type;
}
const std::unordered_map<std::string, std::string> &mount_entry_t::getOptions() const
{
return opts_map;
}
int mount_entry_t::getDumpFrequency() const
{
return freq;
}
int mount_entry_t::getPassNumber() const
{
return passno;
}
void mount_entry_t::parseMountOptions(const std::string &input)
{
std::istringstream iss(input);
std::string token;
while (std::getline(iss, token, ','))
{
std::istringstream tokenStream(token);
std::string key, value;
if (std::getline(tokenStream, key, '='))
{
std::getline(tokenStream, value); // Put what's left in the stream to value, could be empty
opts_map[key] = value;
}
}
}
const std::string &mount_entry_t::getFsName() const { return fsname; }
const std::string &mount_entry_t::getMountPoint() const { return dir; }
const std::string &mount_entry_t::getType() const { return type; }
const std::unordered_map<std::string, std::string> &mount_entry_t::getOptions() const { return opts_map; }
int mount_entry_t::getDumpFrequency() const { return freq; }
int mount_entry_t::getPassNumber() const { return passno; }
std::vector<mount_entry_t> parseMountsFromPath(const char *path)
{
std::vector<mount_entry_t> result;
FILE *file = setmntent(path, "r");
if (file == NULL)
{
LOGE("setmntent(\"%s\", \"r\") returned NULL: %d (%s)", path, errno, strerror(errno));
return result;
}
FILE *file;
ASSERT_EXIT("parseMountsFromPath", (file = setmntent(path, "r")) != NULL, return result);
struct mntent *entry;
while ((entry = getmntent(file)) != NULL)
@@ -81,3 +38,22 @@ std::vector<mount_entry_t> parseMountsFromPath(const char *path)
endmntent(file);
return result;
}
std::unordered_map<std::string, std::string> parseMountOptions(const std::string &input)
{
std::unordered_map<std::string, std::string> ret;
std::istringstream iss(input);
std::string token;
while (std::getline(iss, token, ','))
{
std::istringstream tokenStream(token);
std::string key, value;
if (std::getline(tokenStream, key, '='))
{
std::getline(tokenStream, value); // Put what's left in the stream to value, could be empty
ret[key] = value;
}
}
return ret;
}

View File

@@ -0,0 +1,90 @@
#include <string>
#include <sstream>
#include <fstream>
#include <vector>
#include <unordered_map>
#include "mountinfo_parser.hpp"
#include "mount_parser.hpp"
#include "logging.hpp"
mountinfo_entry_t::mountinfo_entry_t(int mount_id, int parent_id, int major, int minor,
const std::string &root, const std::string &mount_point,
const std::string &mount_options, const std::string &optional_fields,
const std::string &filesystem_type, const std::string &mount_source,
const std::string &super_options)
: mount_id(mount_id), parent_id(parent_id), major(major), minor(minor),
root(root), mount_point(mount_point),
optional_fields(optional_fields), filesystem_type(filesystem_type),
mount_source(mount_source)
{
this->mount_options = parseMountOptions(mount_options);
this->super_options = parseMountOptions(super_options);
}
int mountinfo_entry_t::getMountId() const { return mount_id; }
int mountinfo_entry_t::getParentId() const { return parent_id; }
int mountinfo_entry_t::getMajor() const { return major; }
int mountinfo_entry_t::getMinor() const { return minor; }
const std::string &mountinfo_entry_t::getRoot() const { return root; }
const std::string &mountinfo_entry_t::getMountPoint() const { return mount_point; }
const std::unordered_map<std::string, std::string> &mountinfo_entry_t::getMountOptions() const { return mount_options; }
const std::string &mountinfo_entry_t::getOptionalFields() const { return optional_fields; }
const std::string &mountinfo_entry_t::getFilesystemType() const { return filesystem_type; }
const std::string &mountinfo_entry_t::getMountSource() const { return mount_source; }
const std::unordered_map<std::string, std::string> &mountinfo_entry_t::getSuperOptions() const { return super_options; }
std::vector<mountinfo_entry_t> parseMountinfosFromPath(const char *path)
{
std::vector<mountinfo_entry_t> ret;
std::ifstream ifs(path, std::ifstream::in);
if (!ifs)
{
LOGE("parseMountinfosFromPath could not open file \"%s\"", path);
return ret;
}
for (std::string line; std::getline(ifs, line);)
{
std::istringstream iss(line);
int mount_id, parent_id, major, minor;
std::string root, mount_point, mount_options, optional_fields, filesystem_type, mount_source, super_options;
char colon;
// Read the first 6 fields (major, colon and minor are the same field)
iss >> mount_id >> parent_id >> major >> colon >> minor >> root >> mount_point >> mount_options;
if (iss.fail())
{
LOGE("parseMountinfosFromPath failed to parse the first 6 fields of line: %s", line.c_str());
continue;
}
std::string field;
while (iss >> field && field != "-")
{
optional_fields += " " + field;
}
if (iss.fail())
{
LOGE("parseMountinfosFromPath failed to parse the optional fields of line: %s", line.c_str());
continue;
}
iss >> filesystem_type >> mount_source >> super_options;
if (iss.fail())
{
LOGE("parseMountinfosFromPath failed to parse the last 3 fields of line: %s", line.c_str());
continue;
}
ret.emplace_back(mountinfo_entry_t(mount_id, parent_id, major, minor,
root, mount_point, mount_options,
optional_fields, filesystem_type, mount_source,
super_options));
}
return ret;
}

View File

@@ -1,73 +0,0 @@
#include <string>
#include <vector>
#include <array>
#include <sys/mount.h>
#include "zygisk.hpp"
#include "logging.hpp"
#include "mount_parser.hpp"
constexpr std::array<const char *, 4> fsname_list = {"KSU", "APatch", "magisk", "worker"};
static bool shouldUnmount(const mount_entry_t &info)
{
const auto &mountPoint = info.getMountPoint();
const auto &type = info.getType();
const auto &options = info.getOptions();
// Unmount everything mounted to /data/adb
if (mountPoint.rfind("/data/adb", 0) == 0)
return true;
// Unmount all module overlayfs and tmpfs
bool doesFsnameMatch = std::find(fsname_list.begin(), fsname_list.end(), info.getFsName()) != fsname_list.end();
if ((type == "overlay" || type == "tmpfs") && doesFsnameMatch)
return true;
// Unmount all overlayfs with lowerdir/upperdir/workdir starting with /data/adb
if (type == "overlay")
{
const auto &lowerdir = options.find("lowerdir");
const auto &upperdir = options.find("upperdir");
const auto &workdir = options.find("workdir");
if (lowerdir != options.end() && lowerdir->second.rfind("/data/adb", 0) == 0)
return true;
if (upperdir != options.end() && upperdir->second.rfind("/data/adb", 0) == 0)
return true;
if (workdir != options.end() && workdir->second.rfind("/data/adb", 0) == 0)
return true;
}
return false;
}
void do_unmount()
{
std::vector<std::string> mountPoints;
for (auto &info : parseMountsFromPath("/proc/self/mounts"))
{
if (shouldUnmount(info))
{
mountPoints.push_back(info.getMountPoint());
}
}
// Sort by string lengths, descending
std::sort(mountPoints.begin(), mountPoints.end(), [](const auto &lhs, const auto &rhs)
{ return lhs.size() > rhs.size(); });
for (const auto &mountPoint : mountPoints)
{
if (umount2(mountPoint.c_str(), MNT_DETACH) == 0)
{
LOGD("umount2(\"%s\", MNT_DETACH) returned 0", mountPoint.c_str());
}
else
{
LOGE("umount2(\"%s\", MNT_DETACH) returned -1: %d (%s)", mountPoint.c_str(), errno, strerror(errno));
}
}
}

48
module/jni/utils.cpp Normal file
View File

@@ -0,0 +1,48 @@
#include <string>
#include <format>
#include <unistd.h>
#include <sched.h>
#include <fcntl.h>
#include "map_parser.hpp"
#include "utils.hpp"
#include "android_filesystem_config.h"
#include "zygisk.hpp"
#include "logging.hpp"
bool hookPLTByName(zygisk::Api *api, const std::string &libName, const std::string &symbolName, void *hookFunc, void **origFunc)
{
for (const auto &map : parseMapsFromPath("/proc/self/maps"))
{
if (map.getPathname().ends_with("/" + libName))
{
api->pltHookRegister(map.getDevice(), map.getInode(), symbolName.c_str(), hookFunc, origFunc);
return true;
}
}
return false;
}
int isUserAppUID(int uid)
{
int appid = uid % AID_USER_OFFSET;
if (appid >= AID_APP_START && appid <= AID_APP_END)
return true;
if (appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END)
return true;
return false;
}
bool switchMountNS(int pid)
{
std::string path = std::string("/proc/") + std::to_string(pid) + "/ns/mnt";
int ret, fd;
if ((fd = open(path.c_str(), O_RDONLY)) < 0)
{
return false;
}
ret = setns(fd, 0);
close(fd);
return ret == 0;
}

View File

@@ -3,4 +3,5 @@ name=${moduleName}
version=${versionName}
versionCode=${versionCode}
author=snake-4
description=Zygisk module to hide mounts.
description=A Zygisk module to hide root.
updateJson=https://raw.githubusercontent.com/snake-4/Zygisk-Assistant/main/update_metadata/update.json

View File

@@ -14,6 +14,4 @@ dependencyResolutionManagement {
}
}
include(
":module"
)
include(":module")

View File

@@ -0,0 +1,12 @@
## 2.1.0
+ Added Zygisk hide for Magisk 27.0.
+ Fixed bind mount hiding. ReVanced is fully hidden now.
+ All Systemless Hosts modules are hidden now.
+ Fixed compatibility issues with other modules.
## 2.0.4
+ Fixed an issue causing root to be lost.
+ Fixed potential incompatibilities with other apps.
## 2.0.3
+ Bind mounts are also hidden now.

View File

@@ -0,0 +1,6 @@
{
"version": "v2.0.4",
"versionCode": 204,
"zipUrl": "https://github.com/snake-4/Zygisk-Assistant/releases/download/v2.0.4/Zygisk-Assistant-v2.0.4-7ec3214-release.zip",
"changelog": "https://raw.githubusercontent.com/snake-4/Zygisk-Assistant/main/update_metadata/CHANGELOG.md"
}