AndroidHiddenApiBypass - Bypass restrictions on non-SDK interfaces

Overview

AndroidHiddenApiBypass

Android CI status

Bypass restrictions on non-SDK interfaces.

Why AndroidHiddenApiBypass?

  • Pure Java: no native code used.
  • Reliable: does not rely on specific behaviors, so it will not be blocked like meta-reflection or dexfile.
  • Stable: unsafe, art structs and setHiddenApiExemptions are stable APIs.

How it works (Chinese)

Integration

Gradle:

repositories {
    mavenCentral()
}
dependencies {
    implementation 'org.lsposed.hiddenapibypass:hiddenapibypass:4.1'
}

Usage

  1. Invoke a restricted method:
    HiddenApiBypass.invoke(ApplicationInfo.class, new ApplicationInfo(), "usesNonSdkApi"/*, args*/)
  2. Invoke restricted constructor:
    Object instance = HiddenApiBypass.newInstance(Class.forName("android.app.IActivityManager$Default")/*, args*/);
  3. Get all methods including restricted ones from a class:
    var allMethods = HiddenApiBypass.getDeclaredMethods(ApplicationInfo.class);
    ((Method).stream(allMethods).filter(e -> e.getName().equals("usesNonSdkApi")).findFirst().get()).invoke(new ApplicationInfo());
  4. Get all non-static fields including restricted ones from a class:
    var allInstanceFields = HiddenApiBypass.getInstanceFields(ApplicationInfo.class);
    ((Method).stream(allInstanceFields).filter(e -> e.getName().equals("longVersionCode")).findFirst().get()).get(new ApplicationInfo());
  5. Get all static fields including restricted ones from a class:
    var allStaticFields = HiddenApiBypass.getStaticFields(ApplicationInfo.class);
    ((Method).stream(allInstanceFields).filter(e -> e.getName().equals("HIDDEN_API_ENFORCEMENT_DEFAULT")).findFirst().get()).get(null);
  6. Get specific class method or class constructor
    var ctor = HiddenApiBypass.getDeclaredConstructor(ClipDrawable.class /*, args */);
    var method = HiddenApiBypass.getDeclaredMethod(ApplicationInfo.class, "getHiddenApiEnforcementPolicy" /*, args */);
  7. Add a class to exemption list:
    HiddenApiBypass.addHiddenApiExemptions(
        "Landroid/content/pm/ApplicationInfo;", // one specific class
        "Ldalvik/system" // all classes in packages dalvik.system
        "Lx" // all classes whose full name is started with x
    );
    if you are going to add all classes to exemption list, just leave an empty prefix:
    HiddenApiBypass.addHiddenApiExemptions("");

License

Copyright 2021 LSPosed

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Comments
  • Maybe need to replace the license to GPL v2 with Classpath Exception

    Maybe need to replace the license to GPL v2 with Classpath Exception

    这个文件 应该是 OpenJDK 的一部分,

    AOSP 里面也有类似关于 Unsafe 的 stub,他们在使用的时候都保留了原 Notice ,例如这个: Unsafe.java

    鉴于 GPL 的传染性,也许整个这个项目应该都换成 GPL v2 with Classpath Exception 许可证

    opened by gtf35 4
  • android invoke hide api have  InvocationTargetException in Android 12

    android invoke hide api have InvocationTargetException in Android 12

    my code:

    HiddenApiBypass.addHiddenApiExemptions("");
    Class<?> c = Class.forName("dalvik.system.VMDebug");
    if(android.os.Build.VERSION.SDK_INT>=28) {
                    getInstancesOfClassesMethod = c.getDeclaredMethod("getInstancesOfClasses",
                            Class[].class, Boolean.TYPE);
    }
    //            return (Object[][]) HiddenApiBypass.invoke(
    //                    Class.forName("dalvik.system.VMDebug"),
    //                    null,"getInstancesOfClasses",
    //                    new Object[]{classes, assignable}
    //                    );
                return (Object[][]) getInstancesOfClassesMethod.invoke(
                        null,
                        new Object[]{classes, assignable});
    
    

    This code can run successfully on Android 11, but InvocationTargetException exception on the 12 version 。

    invalid 
    opened by w296488320 3
  • Not working in android level 12

    Not working in android level 12

    hello. I using HokoBlurDrawable and Using method callDrawGLFunction2 in class android.graphics.RecordingCanvas. i try to use this in api 30 to the top.

    invalid 
    opened by SudoDios 3
  • Google is forbidding this way ?

    Google is forbidding this way ?

    The code from art/runtime/java_lang_Class.cc

    ` // Check classes in the java.lang.invoke package. At the time of writing, the // classes of interest are MethodHandles and MethodHandles.Lookup, but this // is subject to change so conservatively cover the entire package. // NB Static initializers within java.lang.invoke are permitted and do not // need further stack inspection. ObjPtrmirror::Class lookup_class = GetClassRootmirror::MethodHandlesLookup(); if ((declaring_class == lookup_class || declaring_class->IsInSamePackage(lookup_class)) && !m->IsClassInitializer()) { return true; }

    `

    invalid 
    opened by zhangjg0201 2
  • 部分类型API需要增强

    部分类型API需要增强

    系统api 约束分为:

    1. @hide
    2. @UnsupportedAppUsage
    3. @SystemApi
    4. @TestApi

    如你示例中,使用ApplicationInfo 中代码进行测试,测试代码如下:

        /**
         * @hide
         */
        public @HiddenApiEnforcementPolicy int getHiddenApiEnforcementPolicy() {}
    
        @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
        private boolean isPackageUnavailable(PackageManager pm) {}
    
       @SystemApi
        public boolean isEncryptionAware() {}
       /** @hide */
        @TestApi
        public boolean isSystemApp() {}
    
    

    测试结果如下:

     java.lang.NoSuchMethodException: android.content.pm.ApplicationInfo.isPackageUnavailable [class android.content.pm.PackageManager]
    
    

    结果: @UnsupportedAppUsage类型兼容需要增强

    invalid 
    opened by hhhaiai 2
  • Use HiddenApiBypass.invoke() or Method.invoke()?

    Use HiddenApiBypass.invoke() or Method.invoke()?

    I noticed that version 3.0 adds a HiddenApiBypass.invoke() function. Is the HiddenApiBypass.invoke() just a helper function, or do we have to change to use this function instead of the traditional Method.invoke() function?

    What about the Field.get()? I don't see a HiddenApiBypass.get() function provided.

    enhancement 
    opened by samlu 1
  • should not print debug messages for the release build

    should not print debug messages for the release build

    I found the getStaticFields() will print out some debug messages. Please remove them or only print messages when BuildConfig.DEBUG is true.

    public static List<Field> getStaticFields(@NonNull Class<?> clazz) {
        ArrayList<Field> list = new ArrayList<>();
        if (clazz.isPrimitive() || clazz.isArray()) return list;
        MethodHandle mh;
        try {
            mh = MethodHandles.lookup().unreflectGetter(Helper.NeverCall.class.getDeclaredField("s"));
        } catch (IllegalAccessException | NoSuchFieldException e) {
            return list;
        }
        long fields = unsafe.getLong(clazz, sFieldOffset);
        if (fields == 0) return list;
        Log.d(TAG, "sfield: " + fields); <----------------------------------------------------------------- debug message
        int numFields = unsafe.getInt(fields);
        if (BuildConfig.DEBUG) Log.d(TAG, clazz + " has " + numFields + " static fields");
        for (int i = 0; i < numFields; i++) {
            long field = fields + i * artFieldSize + artFieldBias;
            Log.d(TAG, "field " + Long.toString(field, 16)); <--------------------------------------------- debug message
            unsafe.putLong(mh, artOffset, field);
            unsafe.putObject(mh, infoOffset, null);
            try {
                MethodHandles.lookup().revealDirect(mh);
            } catch (Throwable ignored) {
            }
            MethodHandleInfo info = (MethodHandleInfo) unsafe.getObject(mh, infoOffset);
            Field member = (Field) unsafe.getObject(info, memberOffset);
            if (BuildConfig.DEBUG)
                Log.v(TAG, "got " + member.getType() + " " + clazz.getTypeName() + "." + member.getName());
            list.add(member);
        }
        return list;
    }
    
    enhancement 
    opened by samlu 0
  • Add a getDeclaredMethod() function

    Add a getDeclaredMethod() function

    Would you add the following API? Method getDeclaredMethod(String name, Class...<?> parameterTypes)

    The reasons are:

    1. we can cache the founded Method in our own class so it does not have to look up methods for each invoke() call
    2. easier for developers to find the polymorphism function

    Public the checkArgsForInvokeMethod() function is also an acceptable workaround.

    enhancement 
    opened by samlu 0
  • Google is forbidding this way ?

    Google is forbidding this way ?

    ` struct FirstExternalCallerVisitor : public StackVisitor { explicit FirstExternalCallerVisitor(Thread* thread) : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames), caller(nullptr) { }

    bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
      ArtMethod *m = GetMethod();
      if (m == nullptr) {
        // Attached native thread. Assume this is *not* boot class path.
        caller = nullptr;
        return false;
      } else if (m->IsRuntimeMethod()) {
        // Internal runtime method, continue walking the stack.
        return true;
      }
    
      ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClass();
      if (declaring_class->IsBootStrapClassLoaded()) {
        if (declaring_class->IsClassClass()) {
          return true;
        }
        **// Check classes in the java.lang.invoke package. At the time of writing, the
        // classes of interest are MethodHandles and MethodHandles.Lookup, but this
        // is subject to change so conservatively cover the entire package.
        // NB Static initializers within java.lang.invoke are permitted and do not
        // need further stack inspection.
        ObjPtr<mirror::Class> lookup_class = GetClassRoot<mirror::MethodHandlesLookup>();
        if ((declaring_class == lookup_class || declaring_class->IsInSamePackage(lookup_class))
            && !m->IsClassInitializer()) {
          return true;
        }**
        // Check for classes in the java.lang.reflect package, except for java.lang.reflect.Proxy.
        // java.lang.reflect.Proxy does its own hidden api checks (https://r.android.com/915496),
        // and walking over this frame would cause a null pointer dereference
        // (e.g. in 691-hiddenapi-proxy).
        ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>();
        if (declaring_class->IsInSamePackage(proxy_class) && declaring_class != proxy_class) {
          if (Runtime::Current()->isChangeEnabled(kPreventMetaReflectionBlacklistAccess)) {
            return true;
          }
        }
      }
    
      caller = m;
      return false;
    }
    

    `

    invalid 
    opened by zhangjg0201 0
Owner
LSPosed
LSPosed
☁ Tencent Cloud IM Server SDK in Java | 腾讯云 IM 服务端 SDK Java 版

Tencent Cloud IM Server SDK in Java The Tencent Cloud IM Server SDK for Java enables Java developers to easily work with Tencent Cloud IM. Requirement

Doocs 64 Dec 23, 2022
A tool to bypass portforwarding using some cheap VServer

Reverse-PortForward This tool bypasses port restrictions of your router using some not-very-powerful server (those are really cheap.) How to set it up

Daniel H. 3 Jan 9, 2022
Version-agnostic and package-agnostic interfaces used in Constellar. Zero strict dependencies, works as a submodule.

bridge Version-agnostic and package-agnostic interfaces used in Constellar. Zero strict dependencies, works as a submodule. Used for cross-compatibili

uranometrical 2 Feb 23, 2022
App to demonstrate the passage of adapter items into activity using interfaces

OnClickListenerExample This application shows how to pass adapter items into an activity using interfaces. The sample data set contains two fields rep

Rohan Bari 1 Feb 2, 2022
A basic shard that demonstrates optional implementations, and interfaces.

Glass - Example A basic shard that demonstrates optional implementations, and interfaces. Basic Information A lot of stuff will be more complex than o

null 1 Feb 13, 2022
A list of direct references to classes and interfaces in the Java Language Specification (3d Ed.)

A list of direct references to classes and interfaces in the Java Language Specification (3d Ed.) and a program to compute the indirectly required classes and interfaces

Joshua Bloch 12 Jun 3, 2022
Non intrusive log4j2 RCE vulnerability patch.

Log4j Patch Resolve the RCE vulnerability caused by JNDI lookup in log4j 2.0~2.14.1. It is licensed under the WTFPL 2.0 license, you can do anything w

Glavo 67 Dec 2, 2022
Non-Blocking Reactive Foundation for the JVM

Reactor Core Non-Blocking Reactive Streams Foundation for the JVM both implementing a Reactive Extensions inspired API and efficient event streaming s

Reactor 4.4k Dec 30, 2022
React Native wrapper around Indy SDK Java and Objective-C wrappers.

React Native Indy SDK React Native Indy SDK wrapper. Installation with npm: $ npm install indy-sdk-react-native --save with Yarn: $ yarn add indy-sdk-

Hyperledger 21 Dec 5, 2022
OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)

OpenAPI Generator Master (5.4.x): 6.0.x (6.0.x): ⭐ ⭐ ⭐ If you would like to contribute, please refer to guidelines and a list of open tasks. ⭐ ⭐ ⭐ ‼️

OpenAPI Tools 14.8k Dec 30, 2022
A Sentry SDK for Java, Android and other JVM languages.

Bad software is everywhere, and we're tired of it. Sentry is on a mission to help developers write better software faster, so we can get back to enjoy

Sentry 912 Dec 28, 2022
React native wrapper for Jitsi Meet SDK Library that rely on the native view (Activity / ViewController)

react-native-jitsi-meet-sdk React native wrapper for Jitsi Meet SDK Library. This Library implements the Jitsi SDK with a native activity on the Andro

null 7 May 2, 2022
This is the official theme SDK for the FairPlayer Music Player for Android.

FairPlayer - Themes SDK This is the official theme SDK for the FairPlayer Music Player for Android. You can download the most recent version of FairPl

Mark Jivko 0 Jan 31, 2022
The world's top-level live sdk...

目录结构说明 本目录包含 Android 版 移动直播 SDK 的Demo 源代码,主要演示接口如何调用以及最基本的功能。 ├─ MLVB-API-Example // MLVB API Example,包括直播推流,直播播放,互动直播 | ├─ App //

LiteAVSDK 18 Jan 5, 2023
Alibaba Cloud Dedicated KMS Transfer SDK for Java can help Java developers to migrate from the KMS keys to the Dedicated KMS keys.

Alibaba Cloud Dedicated KMS Transfer SDK for Java Alibaba Cloud Dedicated KMS Transfer SDK for Java can help Java developers to migrate from the KMS k

Alibaba Cloud 3 May 12, 2022
A demo of Rongcloud uniapp sdk integration for compiling debug-apk in Android Studio

Rongcloud-uniapp-sdk-demo A demo of Rongcloud uniapp sdk integration for compiling debug-apk in Android Studio 这是一个为了给uniapp在Android平台打出debug-apk的demo

Zongkui Guo 1 Oct 13, 2021
The VAST ad sample code provided by HUAWEI Ads Kit describes how to display linear ads by integrating the HUAWEI VAST SDK into your app.

HMS Ads Demo for VAST English | 中文 Table of Contents Introduction Installation Configuration Supported Environments Sample Code Result License Introdu

HMS 11 Jul 16, 2022
SDK java permettant de valider et qualifier un numéro de téléphone calédonien.

❔ phonenumber-validator SDK Java permettant de valider, qualifier un numéro de téléphone calédonien. ⬇️ Import de la dépendance publique Cette dépenda

OPT Nouvelle Caledonie 2 Oct 22, 2022
Java wrapper for Agones client SDK.

agones4j How to Use (Developers) Code final class Server { public static void main( final String[] args ) { final var sdk = new tr.com.in

Infumia LTD 6 Dec 15, 2022