├── .gitattributes ├── .github ├── FUNDING.yml └── ISSUE_TEMPLATE │ └── bug_report.md ├── .gitignore ├── .gitmodules ├── CHANGELOG.md ├── LICENSE ├── README.md ├── build.sh ├── docs └── details.md ├── java ├── .gitignore ├── app │ ├── .gitignore │ ├── build.gradle │ ├── proguard-rules.pro │ └── src │ │ └── main │ │ ├── AndroidManifest.xml │ │ ├── java │ │ └── dev │ │ │ └── kdrag0n │ │ │ └── safetynetfix │ │ │ ├── EntryPoint.kt │ │ │ ├── SecurityHooks.kt │ │ │ ├── proxy │ │ │ ├── ProxyKeyStoreSpi.kt │ │ │ └── ProxyProvider.kt │ │ │ └── util │ │ │ └── Utils.kt │ │ └── res │ │ └── values │ │ └── strings.xml ├── build.gradle ├── gradle.properties ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle ├── magisk ├── META-INF │ └── com │ │ └── google │ │ └── android │ │ ├── update-binary │ │ └── updater-script ├── customize.sh ├── module.prop ├── post-fs-data.sh ├── service.sh └── system.prop ├── update.json └── zygisk ├── .gitignore ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── module ├── .gitignore ├── build.gradle ├── jni │ ├── Android.mk │ ├── Application.mk │ ├── module.cpp │ ├── module.h │ └── zygisk.hpp └── src │ └── main │ └── AndroidManifest.xml └── settings.gradle /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set the default behavior, in case people don't have core.autocrlf set. 2 | * text eol=lf 3 | 4 | # Declare files that will always have CRLF line endings on checkout. 5 | *.cmd text eol=crlf 6 | *.bat text eol=crlf 7 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | patreon: kdrag0n 2 | liberapay: kdrag0n 3 | custom: "https://paypal.me/kdrag0ndonate" 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Report a bug or issue 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | 14 | 15 | **Describe the bug** 16 | A clear and concise description of what the bug is. 17 | 18 | **To reproduce** 19 | Steps to reproduce the behavior: 20 | 1. Go to '...' 21 | 2. Click on '....' 22 | 3. Scroll down to '....' 23 | 4. See error 24 | 25 | **Expected behavior** 26 | A clear and concise description of what you expected to happen. 27 | 28 | **Screenshots** 29 | If applicable, add screenshots to help explain your problem. 30 | 31 | **Device info** 32 | Device model: 33 | Android version: 34 | ROM name/version: 35 | 36 | **Logs** 37 | Connect your phone to a computer and run `adb logcat > issue.log`. Attach the log file to this issue. 38 | 39 | **Additional context** 40 | Add any other context about the problem here. 41 | 42 | **Checklist** 43 | - [ ] All information is present 44 | - [ ] Logs are attached 45 | - [ ] I have tried installing and configuring [MagiskHide Props Config](https://github.com/Magisk-Modules-Repo/MagiskHidePropsConf) 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.zip 3 | *.so 4 | *.dex 5 | 6 | # VS Code Java Language Server 7 | .settings/ 8 | .project 9 | .classpath 10 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "zygisk/module/jni/libcxx"] 2 | path = zygisk/module/jni/libcxx 3 | url = https://github.com/topjohnwu/libcxx.git 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # v2.4.0 2 | 3 | ## Highlights 4 | 5 | - **Play Integrity bypass** without breaking device checks or causing other issues 6 | - Disabled use of hardware attestation on Pixel 7 and newer (@anirudhgupta109) 7 | 8 | ## Other changes 9 | 10 | - Updated instructions for newer Android and Magisk versions 11 | - Better debugging for future development 12 | 13 | **This version only supports Zygisk (Magisk 24 and newer).** 14 | 15 | It's taken a while to find way to bypass Play Integrity that doesn't require spoofing the build fingerprint permanently, but I wanted to make sure this module doesn't cause any unnecessary breakage. Enjoy! 16 | 17 | --- 18 | 19 | # Donate 20 | 21 | **If you found this module helpful, please consider supporting development with a [recurring donation](https://patreon.com/kdrag0n)** for rewards such as early access to updates, exclusive behind-the-scenes development news, and priority support. Alternatively, [you can also **buy me a coffee**](https://paypal.me/kdrag0ndonate). All support is appreciated ❤️ 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2021 Danny Lin 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Universal SafetyNet Fix 2 | 3 | Magisk module to work around Google's SafetyNet and Play Integrity attestation. 4 | 5 | This module works around hardware attestation and updates to SafetyNet and Play Integrity CTS profile checks. You must already be able to pass basic CTS profile attestation, which requires a valid combination of device and model names, build fingerprints, and security patch levels. 6 | 7 | If you still have trouble passing SafetyNet or Play Integrity with this module, spoof the profile of a certified device by copying `ro.product` properties. [MagiskHide Props Config](https://github.com/Magisk-Modules-Repo/MagiskHidePropsConf) is an easy way to do so on Magisk v23 and older. This is a common issue on old devices, custom ROMs, and stock ROMs without GMS certification (e.g. Chinese ROMs). 8 | 9 | Android versions up to 13 are supported, including OEM skins such as Samsung One UI and MIUI. 10 | 11 | ## Download 12 | 13 | **[Download latest version](https://github.com/kdrag0n/safetynet-fix/releases)** 14 | 15 | Install the downloaded module in Magisk Manager, then **enable Zygisk in Magisk settings.** 16 | 17 | There is also a [Riru version](https://github.com/kdrag0n/safetynet-fix/releases/tag/v2.1.3) for Magisk 23 and older, but it is no longer updated. Please update to a current version of Magisk and use the Zygisk version. 18 | 19 | ## How does it work? 20 | 21 | See [Details](docs/details.md) for details about how this module works. 22 | 23 | ## ROM integration 24 | 25 | Ideally, this workaround should be incorporated in custom ROMs instead of injecting code with a Magisk module. See the [ProtonAOSP website](https://protonaosp.org/developers/details/safetynet) for more information. 26 | 27 | ## Support 28 | 29 | If you found this module helpful, please consider supporting development with a **[recurring donation](https://patreon.com/kdrag0n)** on Patreon for benefits such as exclusive behind-the-scenes development news, early access to updates, and priority support. Alternatively, you can also [buy me a coffee](https://paypal.me/kdrag0ndonate). All support is appreciated. 30 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -euo pipefail 4 | 5 | build_mode="${1:-release}" 6 | 7 | cd "$(dirname "$0")" 8 | 9 | pushd zygisk/module 10 | rm -fr libs 11 | debug_mode=1 12 | if [[ "$build_mode" == "release" ]]; then 13 | debug_mode=0 14 | fi 15 | $ANDROID_HOME/ndk/25.2.9519653/ndk-build -j48 NDK_DEBUG=$debug_mode 16 | popd 17 | 18 | pushd java 19 | # Must always be release due to R8 requirement 20 | ./gradlew assembleRelease 21 | popd 22 | 23 | mkdir -p magisk/zygisk 24 | for arch in arm64-v8a armeabi-v7a x86 x86_64 25 | do 26 | cp "zygisk/module/libs/$arch/libsafetynetfix.so" "magisk/zygisk/$arch.so" 27 | done 28 | 29 | pushd magisk 30 | version="$(grep '^version=' module.prop | cut -d= -f2)" 31 | rm -f "../safetynet-fix-$version.zip" classes.dex 32 | unzip "../java/app/build/outputs/apk/release/app-release.apk" "classes.dex" 33 | zip -r9 "../safetynet-fix-$version.zip" . 34 | popd 35 | -------------------------------------------------------------------------------- /docs/details.md: -------------------------------------------------------------------------------- 1 | # How does Universal SafetyNet Fix work? 2 | 3 | Since January 12, 2021, Google Play Services opportunistically uses hardware-backed attestation to improve SafetyNet integrity. It also enforces usage based on the device model name since September 2, 2021. 4 | 5 | This module uses Zygisk to inject code into the Play Services process and register a fake keystore provider that overrides the real one. When Play Services attempts to use key attestation, it throws an exception and pretends that the device lacks support for key attestation. This causes SafetyNet to fall back to basic attestation, which is much weaker and can be bypassed with existing methods. 6 | 7 | However, blocking key attestation alone does not suffice because basic attestation fails on devices that are known by Google to support hardware-backed attestation. This module bypasses the check by appending a space character to the device model name. This has minimal impact on UX when only applied to Play Services, but it's sufficient for bypassing enforcement of hardware-backed attestation. 8 | 9 | This doesn't break other features because key attestation is only blocked for Play Services, and even within Play Services, it's only blocked for SafetyNet code. As a result, other attestation-based features (such as using the device as a security key) continue to work. 10 | -------------------------------------------------------------------------------- /java/.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | .DS_Store 6 | /build 7 | /captures 8 | .externalNativeBuild 9 | .cxx 10 | local.properties 11 | -------------------------------------------------------------------------------- /java/app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /java/app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.application' 3 | id 'kotlin-android' 4 | } 5 | 6 | android { 7 | namespace 'dev.kdrag0n.safetynetfix' 8 | 9 | compileSdk 33 10 | 11 | defaultConfig { 12 | applicationId "dev.kdrag0n.safetynetfix" 13 | minSdk 24 14 | targetSdk 33 15 | versionCode 1 16 | versionName "1.0" 17 | 18 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 19 | } 20 | 21 | buildTypes { 22 | release { 23 | minifyEnabled true 24 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 25 | signingConfig signingConfigs.debug 26 | } 27 | } 28 | compileOptions { 29 | sourceCompatibility JavaVersion.VERSION_1_8 30 | targetCompatibility JavaVersion.VERSION_1_8 31 | } 32 | kotlinOptions { 33 | jvmTarget = '1.8' 34 | } 35 | } 36 | 37 | dependencies { 38 | implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.8.10' 39 | } 40 | -------------------------------------------------------------------------------- /java/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | 23 | -keep class dev.kdrag0n.safetynetfix.EntryPoint { 24 | public static void init(); 25 | } 26 | 27 | -keepclassmembers class dev.kdrag0n.safetynetfix.proxy.ProxyKeyStoreSpi { 28 | public (...); 29 | } 30 | 31 | # Remove @DebugMetadata annotations to avoid leaking info 32 | # Source: https://proandroiddev.com/kotlin-cleaning-java-bytecode-before-release-9567d4c63911 33 | -checkdiscard @interface kotlin.coroutines.jvm.internal.DebugMetadata 34 | -assumenosideeffects public class kotlin.coroutines.jvm.internal.BaseContinuationImpl { 35 | private kotlin.coroutines.jvm.internal.DebugMetadata getDebugMetadataAnnotation() return null; 36 | public java.lang.StackTraceElement getStackTraceElement() return null; 37 | public java.lang.String[] getSpilledVariableFieldMapping() return null; 38 | } 39 | 40 | -assumenosideeffects class kotlin.jvm.internal.Intrinsics { 41 | # Remove verbose NPE intrinsics to reduce code size and avoid leaking info 42 | # Source: https://issuetracker.google.com/issues/190489514 43 | static void checkParameterIsNotNull(java.lang.Object, java.lang.String); 44 | static void checkNotNullParameter(java.lang.Object, java.lang.String); 45 | static void checkFieldIsNotNull(java.lang.Object, java.lang.String); 46 | static void checkFieldIsNotNull(java.lang.Object, java.lang.String, java.lang.String); 47 | static void checkReturnedValueIsNotNull(java.lang.Object, java.lang.String); 48 | static void checkReturnedValueIsNotNull(java.lang.Object, java.lang.String, java.lang.String); 49 | static void checkNotNullExpressionValue(java.lang.Object, java.lang.String); 50 | static void checkExpressionValueIsNotNull(java.lang.Object, java.lang.String); 51 | static void checkNotNull(java.lang.Object); 52 | static void checkNotNull(java.lang.Object, java.lang.String); 53 | 54 | # Remove remaining stray calls to stringPlus 55 | static java.lang.String stringPlus(java.lang.String, java.lang.Object); 56 | } 57 | -------------------------------------------------------------------------------- /java/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /java/app/src/main/java/dev/kdrag0n/safetynetfix/EntryPoint.kt: -------------------------------------------------------------------------------- 1 | package dev.kdrag0n.safetynetfix 2 | 3 | @Suppress("unused") 4 | object EntryPoint { 5 | @JvmStatic 6 | fun init() { 7 | try { 8 | logDebug("Entry point: Initializing SafetyNet patches") 9 | SecurityHooks.init() 10 | } catch (e: Throwable) { 11 | // Throwing an exception would require the JNI code to handle exceptions, so just catch 12 | // everything here. 13 | logDebug("Error in entry point", e) 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/app/src/main/java/dev/kdrag0n/safetynetfix/SecurityHooks.kt: -------------------------------------------------------------------------------- 1 | package dev.kdrag0n.safetynetfix 2 | 3 | import dev.kdrag0n.safetynetfix.proxy.ProxyKeyStoreSpi 4 | import dev.kdrag0n.safetynetfix.proxy.ProxyProvider 5 | import java.security.KeyStore 6 | import java.security.KeyStoreSpi 7 | import java.security.Security 8 | 9 | internal object SecurityHooks { 10 | const val PROVIDER_NAME = "AndroidKeyStore" 11 | 12 | fun init() { 13 | logDebug("Initializing SecurityBridge") 14 | 15 | val realProvider = Security.getProvider(PROVIDER_NAME) 16 | val realKeystore = KeyStore.getInstance(PROVIDER_NAME) 17 | val realSpi = realKeystore.get("keyStoreSpi") 18 | logDebug("Real provider=$realProvider, keystore=$realKeystore, spi=$realSpi") 19 | 20 | val provider = ProxyProvider(realProvider) 21 | logDebug("Removing real provider") 22 | Security.removeProvider(PROVIDER_NAME) 23 | logDebug("Inserting provider $provider") 24 | Security.insertProviderAt(provider, 1) 25 | ProxyKeyStoreSpi.androidImpl = realSpi 26 | logDebug("Security hooks installed") 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /java/app/src/main/java/dev/kdrag0n/safetynetfix/proxy/ProxyKeyStoreSpi.kt: -------------------------------------------------------------------------------- 1 | package dev.kdrag0n.safetynetfix.proxy 2 | 3 | import dev.kdrag0n.safetynetfix.logDebug 4 | import java.io.InputStream 5 | import java.io.OutputStream 6 | import java.security.Key 7 | import java.security.KeyStoreSpi 8 | import java.security.cert.Certificate 9 | import java.util.* 10 | 11 | class ProxyKeyStoreSpi private constructor( 12 | private val orig: KeyStoreSpi, 13 | ) : KeyStoreSpi() { 14 | @Suppress("unused") 15 | constructor() : this(androidImpl!!) 16 | 17 | init { 18 | logDebug("Init proxy KeyStore SPI") 19 | } 20 | 21 | // Avoid breaking other, legitimate uses of key attestation in Google Play Services, e.g. 22 | // - com.google.android.gms.auth.cryptauth.register.ReEnrollmentChimeraService 23 | // - tk_trace.129-RegisterForKeyPairOperation 24 | private fun isCallerDeniedOrSafetyNet(): Boolean { 25 | var isGMS = false 26 | 27 | // SafetyNet stack trace example: 28 | // a.a.engineGetCertificateChain(Unknown Source:15) 29 | // java.security.KeyStore.getCertificateChain(KeyStore.java:1087) 30 | // com.google.ccc.abuse.droidguard.DroidGuard.initNative(Native Method) 31 | // com.google.ccc.abuse.droidguard.DroidGuard.init(DroidGuard.java:447) 32 | // java.lang.reflect.Method.invoke(Native Method) 33 | // xvq.b(:com.google.android.gms@212621053@21.26.21 (190400-387928701):1) 34 | // xuc.a(:com.google.android.gms@212621053@21.26.21 (190400-387928701):5) 35 | // xuc.eX(:com.google.android.gms@212621053@21.26.21 (190400-387928701):1) 36 | // dzx.onTransact(:com.google.android.gms@212621053@21.26.21 (190400-387928701):8) 37 | // android.os.Binder.execTransactInternal(Binder.java:1179) 38 | // android.os.Binder.execTransact(Binder.java:1143) 39 | for (it in Thread.currentThread().stackTrace) { 40 | logDebug("Stack trace element: $it") 41 | 42 | if (it.className.contains("DroidGuard", ignoreCase = true)) { 43 | return true 44 | } 45 | 46 | if (!isGMS && it.className.contains("com.google.android.gms", ignoreCase = true)) { 47 | isGMS = true 48 | } 49 | } 50 | 51 | return !isGMS 52 | } 53 | 54 | override fun engineGetCertificateChain(alias: String?): Array? { 55 | logDebug("Proxy key store: get certificate chain") 56 | 57 | if (isCallerDeniedOrSafetyNet()) { 58 | logDebug("Blocking call") 59 | throw UnsupportedOperationException() 60 | } else { 61 | logDebug("Allowing call") 62 | return orig.engineGetCertificateChain(alias) 63 | } 64 | } 65 | 66 | // Direct delegation. We have to do this manually because the Kotlin compiler can only do it 67 | // for interfaces, not abstract classes. 68 | override fun engineGetKey(alias: String?, password: CharArray?): Key? = orig.engineGetKey(alias, password) 69 | override fun engineGetCertificate(alias: String?): Certificate? = orig.engineGetCertificate(alias) 70 | override fun engineGetCreationDate(alias: String?): Date? = orig.engineGetCreationDate(alias) 71 | override fun engineSetKeyEntry(alias: String?, key: Key?, password: CharArray?, chain: Array?) = orig.engineSetKeyEntry(alias, key, password, chain) 72 | override fun engineSetKeyEntry(alias: String?, key: ByteArray?, chain: Array?) = orig.engineSetKeyEntry(alias, key, chain) 73 | override fun engineSetCertificateEntry(alias: String?, cert: Certificate?) = orig.engineSetCertificateEntry(alias, cert) 74 | override fun engineDeleteEntry(alias: String?) = orig.engineDeleteEntry(alias) 75 | override fun engineAliases(): Enumeration? = orig.engineAliases() 76 | override fun engineContainsAlias(alias: String?) = orig.engineContainsAlias(alias) 77 | override fun engineSize() = orig.engineSize() 78 | override fun engineIsKeyEntry(alias: String?) = orig.engineIsKeyEntry(alias) 79 | override fun engineIsCertificateEntry(alias: String?) = orig.engineIsCertificateEntry(alias) 80 | override fun engineGetCertificateAlias(cert: Certificate?): String? = orig.engineGetCertificateAlias(cert) 81 | override fun engineStore(stream: OutputStream?, password: CharArray?) = orig.engineStore(stream, password) 82 | override fun engineLoad(stream: InputStream?, password: CharArray?) = orig.engineLoad(stream, password) 83 | 84 | companion object { 85 | @Volatile internal var androidImpl: KeyStoreSpi? = null 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /java/app/src/main/java/dev/kdrag0n/safetynetfix/proxy/ProxyProvider.kt: -------------------------------------------------------------------------------- 1 | package dev.kdrag0n.safetynetfix.proxy 2 | 3 | import android.os.Build 4 | import dev.kdrag0n.safetynetfix.SecurityHooks 5 | import dev.kdrag0n.safetynetfix.logDebug 6 | import java.security.Provider 7 | import kotlin.concurrent.thread 8 | 9 | // This is mostly just a pass-through provider that exists to change the provider's ClassLoader. 10 | // This works because Service looks up the class by name from the *provider* ClassLoader, not 11 | // necessarily the bootstrap one. 12 | class ProxyProvider( 13 | orig: Provider, 14 | ) : Provider(orig.name, orig.version, orig.info) { 15 | init { 16 | logDebug("Init proxy provider - wrapping $orig") 17 | 18 | putAll(orig) 19 | this["KeyStore.${SecurityHooks.PROVIDER_NAME}"] = ProxyKeyStoreSpi::class.java.name 20 | } 21 | 22 | override fun getService(type: String?, algorithm: String?): Service? { 23 | logDebug("Provider: get service - type=$type algorithm=$algorithm") 24 | if (type == "KeyStore") { 25 | 26 | val origProduct = Build.PRODUCT 27 | val patchedProduct = "marlin" 28 | 29 | val origDevice = Build.DEVICE 30 | val patchedDevice = "marlin" 31 | 32 | val origModel = Build.MODEL 33 | val patchedModel = "Pixel XL" 34 | 35 | val origFingerprint = Build.FINGERPRINT 36 | val patchedFingerprint = "google/marlin/marlin:7.1.2/NJH47F/4146041:user/release-keys" 37 | 38 | logDebug("Patch PRODUCT for KeyStore $origProduct -> $patchedProduct") 39 | Build::class.java.getDeclaredField("PRODUCT").let { field -> 40 | field.isAccessible = true 41 | field.set(null, patchedProduct) 42 | } 43 | logDebug("Patch DEVICE for KeyStore $origDevice -> $patchedDevice") 44 | Build::class.java.getDeclaredField("DEVICE").let { field -> 45 | field.isAccessible = true 46 | field.set(null, patchedDevice) 47 | } 48 | logDebug("Patch MODEL for KeyStore $origModel -> $patchedModel") 49 | Build::class.java.getDeclaredField("MODEL").let { field -> 50 | field.isAccessible = true 51 | field.set(null, patchedModel) 52 | } 53 | logDebug("Patch FINGERPRINT for KeyStore $origFingerprint -> $patchedFingerprint") 54 | Build::class.java.getDeclaredField("FINGERPRINT").let { field -> 55 | field.isAccessible = true 56 | field.set(null, patchedFingerprint) 57 | } 58 | } 59 | return super.getService(type, algorithm) 60 | } 61 | 62 | override fun getServices(): MutableSet? { 63 | logDebug("Get services") 64 | return super.getServices() 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /java/app/src/main/java/dev/kdrag0n/safetynetfix/util/Utils.kt: -------------------------------------------------------------------------------- 1 | package dev.kdrag0n.safetynetfix 2 | 3 | import android.os.Build 4 | import android.app.Application 5 | import android.util.Log 6 | 7 | private const val DEBUG = true 8 | private const val TAG = "SNFix/Java" 9 | 10 | internal fun Any.get(name: String) = this::class.java.getDeclaredField(name).let { field -> 11 | field.isAccessible = true 12 | @Suppress("unchecked_cast") 13 | field.get(this) as T 14 | } 15 | 16 | internal fun logDebug(msg: String) { 17 | if (DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { 18 | Log.d(TAG, "[${Application.getProcessName()}] $msg") 19 | } 20 | } 21 | 22 | internal fun logDebug(msg: String, e: Throwable) { 23 | if (DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { 24 | Log.d(TAG, "[${Application.getProcessName()}] $msg", e) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /java/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Universal SafetyNet Fix 3 | 4 | -------------------------------------------------------------------------------- /java/build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | buildscript { 3 | repositories { 4 | google() 5 | mavenCentral() 6 | } 7 | dependencies { 8 | classpath "com.android.tools.build:gradle:7.4.1" 9 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.10" 10 | 11 | // NOTE: Do not place your application dependencies here; they belong 12 | // in the individual module build.gradle files 13 | } 14 | } 15 | 16 | task clean(type: Delete) { 17 | delete rootProject.buildDir 18 | } 19 | -------------------------------------------------------------------------------- /java/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app"s APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | # Kotlin code style for this project: "official" or "obsolete": 21 | kotlin.code.style=official 22 | -------------------------------------------------------------------------------- /java/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PaperStrike/safetynet-fix/40791425de2903ffc2c0f1bffb004ee9234770de/java/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /java/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip 4 | networkTimeout=10000 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /java/gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 147 | # shellcheck disable=SC3045 148 | MAX_FD=$( ulimit -H -n ) || 149 | warn "Could not query maximum file descriptor limit" 150 | esac 151 | case $MAX_FD in #( 152 | '' | soft) :;; #( 153 | *) 154 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 155 | # shellcheck disable=SC3045 156 | ulimit -n "$MAX_FD" || 157 | warn "Could not set maximum file descriptor limit to $MAX_FD" 158 | esac 159 | fi 160 | 161 | # Collect all arguments for the java command, stacking in reverse order: 162 | # * args from the command line 163 | # * the main class name 164 | # * -classpath 165 | # * -D...appname settings 166 | # * --module-path (only if needed) 167 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 168 | 169 | # For Cygwin or MSYS, switch paths to Windows format before running java 170 | if "$cygwin" || "$msys" ; then 171 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 172 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 173 | 174 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 175 | 176 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 177 | for arg do 178 | if 179 | case $arg in #( 180 | -*) false ;; # don't mess with options #( 181 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 182 | [ -e "$t" ] ;; #( 183 | *) false ;; 184 | esac 185 | then 186 | arg=$( cygpath --path --ignore --mixed "$arg" ) 187 | fi 188 | # Roll the args list around exactly as many times as the number of 189 | # args, so each arg winds up back in the position where it started, but 190 | # possibly modified. 191 | # 192 | # NB: a `for` loop captures its iteration list before it begins, so 193 | # changing the positional parameters here affects neither the number of 194 | # iterations, nor the values presented in `arg`. 195 | shift # remove old arg 196 | set -- "$@" "$arg" # push replacement arg 197 | done 198 | fi 199 | 200 | # Collect all arguments for the java command; 201 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 202 | # shell script including quotes and variable substitutions, so put them in 203 | # double quotes to make sure that they get re-expanded; and 204 | # * put everything else in single quotes, so that it's not re-expanded. 205 | 206 | set -- \ 207 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 208 | -classpath "$CLASSPATH" \ 209 | org.gradle.wrapper.GradleWrapperMain \ 210 | "$@" 211 | 212 | # Stop when "xargs" is not available. 213 | if ! command -v xargs >/dev/null 2>&1 214 | then 215 | die "xargs is not available" 216 | fi 217 | 218 | # Use "xargs" to parse quoted args. 219 | # 220 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 221 | # 222 | # In Bash we could simply go: 223 | # 224 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 225 | # set -- "${ARGS[@]}" "$@" 226 | # 227 | # but POSIX shell has neither arrays nor command substitution, so instead we 228 | # post-process each arg (as a line of input to sed) to backslash-escape any 229 | # character that might be a shell metacharacter, then use eval to reverse 230 | # that process (while maintaining the separation between arguments), and wrap 231 | # the whole thing up as a single "set" statement. 232 | # 233 | # This will of course break if any of these variables contains a newline or 234 | # an unmatched quote. 235 | # 236 | 237 | eval "set -- $( 238 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 239 | xargs -n1 | 240 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 241 | tr '\n' ' ' 242 | )" '"$@"' 243 | 244 | exec "$JAVACMD" "$@" 245 | -------------------------------------------------------------------------------- /java/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /java/settings.gradle: -------------------------------------------------------------------------------- 1 | dependencyResolutionManagement { 2 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 3 | repositories { 4 | google() 5 | mavenCentral() 6 | } 7 | } 8 | rootProject.name = "Universal SafetyNet Fix" 9 | include ':app' 10 | -------------------------------------------------------------------------------- /magisk/META-INF/com/google/android/update-binary: -------------------------------------------------------------------------------- 1 | #!/sbin/sh 2 | 3 | ################# 4 | # Initialization 5 | ################# 6 | 7 | umask 022 8 | 9 | # echo before loading util_functions 10 | ui_print() { echo "$1"; } 11 | 12 | require_new_magisk() { 13 | ui_print "*******************************" 14 | ui_print " Please install Magisk v20.4+! " 15 | ui_print "*******************************" 16 | exit 1 17 | } 18 | 19 | ######################### 20 | # Load util_functions.sh 21 | ######################### 22 | 23 | OUTFD=$2 24 | ZIPFILE=$3 25 | 26 | mount /data 2>/dev/null 27 | 28 | [ -f /data/adb/magisk/util_functions.sh ] || require_new_magisk 29 | . /data/adb/magisk/util_functions.sh 30 | [ $MAGISK_VER_CODE -lt 20400 ] && require_new_magisk 31 | 32 | install_module 33 | exit 0 34 | -------------------------------------------------------------------------------- /magisk/META-INF/com/google/android/updater-script: -------------------------------------------------------------------------------- 1 | #MAGISK 2 | -------------------------------------------------------------------------------- /magisk/customize.sh: -------------------------------------------------------------------------------- 1 | #!/system/bin/sh 2 | 3 | # Android 8.0 or newer 4 | if [[ "$(getprop ro.build.version.sdk)" -lt 26 ]]; then 5 | ui_print "" 6 | ui_print "Functionality is limited on Android 7 and older." 7 | ui_print "Hardware-backed attestation will not be disabled." 8 | ui_print "" 9 | 10 | # Remove Zygisk module, but keep props and scripts 11 | rm -fr "$MODPATH/zygisk" 12 | fi 13 | 14 | chmod 755 "$MODPATH/service.sh" "$MODPATH/post-fs-data.sh" 15 | -------------------------------------------------------------------------------- /magisk/module.prop: -------------------------------------------------------------------------------- 1 | id=safetynet-fix 2 | name=Universal SafetyNet Fix 3 | version=v2.4.0 4 | versionCode=20400 5 | author=kdrag0n 6 | description=A universal fix for SafetyNet and Play Integrity on Android 8–13 devices with hardware attestation. 7 | updateJson=https://raw.githubusercontent.com/kdrag0n/safetynet-fix/master/update.json 8 | -------------------------------------------------------------------------------- /magisk/post-fs-data.sh: -------------------------------------------------------------------------------- 1 | #!/system/bin/sh 2 | 3 | # Remove Play Services from the Magisk Denylist when set to enforcing. 4 | if magisk --denylist status; then 5 | magisk --denylist rm com.google.android.gms 6 | fi 7 | -------------------------------------------------------------------------------- /magisk/service.sh: -------------------------------------------------------------------------------- 1 | #!/system/bin/sh 2 | # Conditional MagiskHide properties 3 | 4 | maybe_set_prop() { 5 | local prop="$1" 6 | local contains="$2" 7 | local value="$3" 8 | 9 | if [[ "$(getprop "$prop")" == *"$contains"* ]]; then 10 | resetprop "$prop" "$value" 11 | fi 12 | } 13 | 14 | # Magisk recovery mode 15 | maybe_set_prop ro.bootmode recovery unknown 16 | maybe_set_prop ro.boot.mode recovery unknown 17 | maybe_set_prop vendor.boot.mode recovery unknown 18 | 19 | # MIUI cross-region flash 20 | maybe_set_prop ro.boot.hwc CN GLOBAL 21 | maybe_set_prop ro.boot.hwcountry China GLOBAL 22 | 23 | resetprop --delete ro.build.selinux 24 | 25 | # SELinux permissive 26 | if [[ "$(cat /sys/fs/selinux/enforce)" == "0" ]]; then 27 | chmod 640 /sys/fs/selinux/enforce 28 | chmod 440 /sys/fs/selinux/policy 29 | fi 30 | 31 | # Late props which must be set after boot_completed 32 | { 33 | until [[ "$(getprop sys.boot_completed)" == "1" ]]; do 34 | sleep 1 35 | done 36 | 37 | # Avoid breaking Realme fingerprint scanners 38 | resetprop ro.boot.flash.locked 1 39 | 40 | # Avoid breaking Oppo fingerprint scanners 41 | resetprop ro.boot.vbmeta.device_state locked 42 | 43 | # Avoid breaking OnePlus display modes/fingerprint scanners 44 | resetprop vendor.boot.verifiedbootstate green 45 | 46 | # Safetynet (avoid breaking OnePlus display modes/fingerprint scanners on OOS 12) 47 | resetprop ro.boot.verifiedbootstate green 48 | resetprop ro.boot.veritymode enforcing 49 | resetprop vendor.boot.vbmeta.device_state locked 50 | 51 | # Avoid breaking encryption, set shipping level to 32 for devices >=33 to allow for software attestation 52 | if [[ "$(getprop ro.product.first_api_level)" -ge 33 ]]; then 53 | resetprop ro.product.first_api_level 32 54 | fi 55 | }& 56 | -------------------------------------------------------------------------------- /magisk/system.prop: -------------------------------------------------------------------------------- 1 | # RootBeer, Microsoft 2 | ro.build.tags=release-keys 3 | 4 | # Samsung 5 | ro.boot.warranty_bit=0 6 | ro.vendor.boot.warranty_bit=0 7 | ro.vendor.warranty_bit=0 8 | ro.warranty_bit=0 9 | 10 | # OnePlus 11 | ro.is_ever_orange=0 12 | 13 | # Other 14 | ro.build.type=user 15 | ro.debuggable=0 16 | ro.secure=1 17 | -------------------------------------------------------------------------------- /update.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "v2.4.0", 3 | "versionCode": 20400, 4 | "zipUrl": "https://github.com/kdrag0n/safetynet-fix/releases/download/v2.4.0/safetynet-fix-v2.4.0.zip", 5 | "changelog": "https://raw.githubusercontent.com/kdrag0n/safetynet-fix/master/CHANGELOG.md" 6 | } 7 | -------------------------------------------------------------------------------- /zygisk/.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | .DS_Store 6 | /build 7 | /captures 8 | .externalNativeBuild 9 | .cxx 10 | local.properties 11 | -------------------------------------------------------------------------------- /zygisk/build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | buildscript { 3 | repositories { 4 | google() 5 | mavenCentral() 6 | } 7 | dependencies { 8 | classpath "com.android.tools.build:gradle:7.4.1" 9 | 10 | // NOTE: Do not place your application dependencies here; they belong 11 | // in the individual module build.gradle files 12 | } 13 | } 14 | 15 | task clean(type: Delete) { 16 | delete rootProject.buildDir 17 | } 18 | -------------------------------------------------------------------------------- /zygisk/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app"s APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | -------------------------------------------------------------------------------- /zygisk/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PaperStrike/safetynet-fix/40791425de2903ffc2c0f1bffb004ee9234770de/zygisk/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /zygisk/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip 4 | networkTimeout=10000 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /zygisk/gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 147 | # shellcheck disable=SC3045 148 | MAX_FD=$( ulimit -H -n ) || 149 | warn "Could not query maximum file descriptor limit" 150 | esac 151 | case $MAX_FD in #( 152 | '' | soft) :;; #( 153 | *) 154 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 155 | # shellcheck disable=SC3045 156 | ulimit -n "$MAX_FD" || 157 | warn "Could not set maximum file descriptor limit to $MAX_FD" 158 | esac 159 | fi 160 | 161 | # Collect all arguments for the java command, stacking in reverse order: 162 | # * args from the command line 163 | # * the main class name 164 | # * -classpath 165 | # * -D...appname settings 166 | # * --module-path (only if needed) 167 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 168 | 169 | # For Cygwin or MSYS, switch paths to Windows format before running java 170 | if "$cygwin" || "$msys" ; then 171 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 172 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 173 | 174 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 175 | 176 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 177 | for arg do 178 | if 179 | case $arg in #( 180 | -*) false ;; # don't mess with options #( 181 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 182 | [ -e "$t" ] ;; #( 183 | *) false ;; 184 | esac 185 | then 186 | arg=$( cygpath --path --ignore --mixed "$arg" ) 187 | fi 188 | # Roll the args list around exactly as many times as the number of 189 | # args, so each arg winds up back in the position where it started, but 190 | # possibly modified. 191 | # 192 | # NB: a `for` loop captures its iteration list before it begins, so 193 | # changing the positional parameters here affects neither the number of 194 | # iterations, nor the values presented in `arg`. 195 | shift # remove old arg 196 | set -- "$@" "$arg" # push replacement arg 197 | done 198 | fi 199 | 200 | # Collect all arguments for the java command; 201 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 202 | # shell script including quotes and variable substitutions, so put them in 203 | # double quotes to make sure that they get re-expanded; and 204 | # * put everything else in single quotes, so that it's not re-expanded. 205 | 206 | set -- \ 207 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 208 | -classpath "$CLASSPATH" \ 209 | org.gradle.wrapper.GradleWrapperMain \ 210 | "$@" 211 | 212 | # Stop when "xargs" is not available. 213 | if ! command -v xargs >/dev/null 2>&1 214 | then 215 | die "xargs is not available" 216 | fi 217 | 218 | # Use "xargs" to parse quoted args. 219 | # 220 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 221 | # 222 | # In Bash we could simply go: 223 | # 224 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 225 | # set -- "${ARGS[@]}" "$@" 226 | # 227 | # but POSIX shell has neither arrays nor command substitution, so instead we 228 | # post-process each arg (as a line of input to sed) to backslash-escape any 229 | # character that might be a shell metacharacter, then use eval to reverse 230 | # that process (while maintaining the separation between arguments), and wrap 231 | # the whole thing up as a single "set" statement. 232 | # 233 | # This will of course break if any of these variables contains a newline or 234 | # an unmatched quote. 235 | # 236 | 237 | eval "set -- $( 238 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 239 | xargs -n1 | 240 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 241 | tr '\n' ' ' 242 | )" '"$@"' 243 | 244 | exec "$JAVACMD" "$@" 245 | -------------------------------------------------------------------------------- /zygisk/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /zygisk/module/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | /libs 3 | /obj 4 | -------------------------------------------------------------------------------- /zygisk/module/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.library' 3 | } 4 | 5 | android { 6 | externalNativeBuild { 7 | ndkBuild { 8 | path("jni/Android.mk") 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /zygisk/module/jni/Android.mk: -------------------------------------------------------------------------------- 1 | LOCAL_PATH := $(call my-dir) 2 | 3 | include $(CLEAR_VARS) 4 | LOCAL_MODULE := safetynetfix 5 | LOCAL_SRC_FILES := module.cpp 6 | LOCAL_STATIC_LIBRARIES := libcxx 7 | LOCAL_LDLIBS := -llog 8 | include $(BUILD_SHARED_LIBRARY) 9 | 10 | include jni/libcxx/Android.mk 11 | 12 | # If you do not want to use libc++, link to system stdc++ 13 | # so that you can at least call the new operator in your code 14 | 15 | # include $(CLEAR_VARS) 16 | # LOCAL_MODULE := example 17 | # LOCAL_SRC_FILES := example.cpp 18 | # LOCAL_LDLIBS := -llog -lstdc++ 19 | # include $(BUILD_SHARED_LIBRARY) 20 | -------------------------------------------------------------------------------- /zygisk/module/jni/Application.mk: -------------------------------------------------------------------------------- 1 | APP_ABI := armeabi-v7a arm64-v8a x86 x86_64 2 | APP_CPPFLAGS := -std=c++17 -fno-exceptions -fno-rtti -fvisibility=hidden -fvisibility-inlines-hidden 3 | APP_STL := none 4 | APP_PLATFORM := android-21 5 | -------------------------------------------------------------------------------- /zygisk/module/jni/module.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include "zygisk.hpp" 10 | #include "module.h" 11 | 12 | namespace safetynetfix { 13 | 14 | class SafetyNetFixModule : public zygisk::ModuleBase { 15 | public: 16 | void onLoad(zygisk::Api *api, JNIEnv *env) override { 17 | this->api = api; 18 | this->env = env; 19 | } 20 | 21 | void preAppSpecialize(zygisk::AppSpecializeArgs *args) override { 22 | const char *rawProcess = env->GetStringUTFChars(args->nice_name, nullptr); 23 | if (rawProcess == nullptr) { 24 | return; 25 | } 26 | 27 | std::string process(rawProcess); 28 | env->ReleaseStringUTFChars(args->nice_name, rawProcess); 29 | 30 | preSpecialize(process); 31 | } 32 | 33 | void postAppSpecialize(const zygisk::AppSpecializeArgs *args) override { 34 | // Inject if module was loaded, otherwise this would've been unloaded by now (for non-GMS) 35 | if (!moduleDex.empty()) { 36 | LOGD("Injecting payload..."); 37 | injectPayload(); 38 | LOGI("Payload injected"); 39 | } 40 | } 41 | 42 | void preServerSpecialize(zygisk::ServerSpecializeArgs *args) override { 43 | // Never tamper with system_server 44 | api->setOption(zygisk::DLCLOSE_MODULE_LIBRARY); 45 | } 46 | 47 | private: 48 | zygisk::Api *api; 49 | JNIEnv *env; 50 | 51 | std::vector moduleDex; 52 | 53 | static int receiveFile(int remote_fd, std::vector& buf) { 54 | off_t size; 55 | int ret = read(remote_fd, &size, sizeof(size)); 56 | if (ret < 0) { 57 | LOGE("Failed to read size"); 58 | return -1; 59 | } 60 | 61 | buf.resize(size); 62 | 63 | int bytesReceived = 0; 64 | while (bytesReceived < size) { 65 | ret = read(remote_fd, buf.data() + bytesReceived, size - bytesReceived); 66 | if (ret < 0) { 67 | LOGE("Failed to read data"); 68 | return -1; 69 | } 70 | 71 | bytesReceived += ret; 72 | } 73 | 74 | return bytesReceived; 75 | } 76 | 77 | void loadPayload() { 78 | auto fd = api->connectCompanion(); 79 | 80 | auto size = receiveFile(fd, moduleDex); 81 | LOGD("Loaded module payload: %d bytes", size); 82 | 83 | close(fd); 84 | } 85 | 86 | void preSpecialize(const std::string& process) { 87 | api->setOption(zygisk::DLCLOSE_MODULE_LIBRARY); 88 | 89 | // Only touch denied and GMS 90 | auto deny = (api->getFlags() & zygisk::PROCESS_ON_DENYLIST) != 0; 91 | if (!deny && process.rfind("com.google.android.gms", 0) != 0) { 92 | return; 93 | } 94 | 95 | // Force DenyList unmounting for all touching processes 96 | api->setOption(zygisk::FORCE_DENYLIST_UNMOUNT); 97 | 98 | // The unstable process is where SafetyNet attestation actually runs, so we only need to 99 | // spoof the model in that process. Leaving other processes alone fixes various issues 100 | // caused by model detection and flag provisioning, such as broken weather with the new 101 | // smartspace on Android 12. 102 | if (deny || process == "com.google.android.gms.unstable") { 103 | // Load the payload, but don't inject it yet until after specialization 104 | // Otherwise, specialization fails if any code from the payload still happens to be 105 | // running 106 | LOGD("Loading payload..."); 107 | loadPayload(); 108 | LOGD("Payload loaded"); 109 | } 110 | } 111 | 112 | void injectPayload() { 113 | // First, get the system classloader 114 | LOGD("get system classloader"); 115 | auto clClass = env->FindClass("java/lang/ClassLoader"); 116 | auto getSystemClassLoader = env->GetStaticMethodID(clClass, "getSystemClassLoader", 117 | "()Ljava/lang/ClassLoader;"); 118 | auto systemClassLoader = env->CallStaticObjectMethod(clClass, getSystemClassLoader); 119 | 120 | // Assuming we have a valid mapped module, load it. This is similar to the approach used for 121 | // Dynamite modules in GmsCompat, except we can use InMemoryDexClassLoader directly instead of 122 | // tampering with DelegateLastClassLoader's DexPathList. 123 | LOGD("create buffer"); 124 | auto buf = env->NewDirectByteBuffer(moduleDex.data(), moduleDex.size()); 125 | LOGD("create class loader"); 126 | auto dexClClass = env->FindClass("dalvik/system/InMemoryDexClassLoader"); 127 | auto dexClInit = env->GetMethodID(dexClClass, "", 128 | "(Ljava/nio/ByteBuffer;Ljava/lang/ClassLoader;)V"); 129 | auto dexCl = env->NewObject(dexClClass, dexClInit, buf, systemClassLoader); 130 | 131 | // Load the class 132 | LOGD("load class"); 133 | auto loadClass = env->GetMethodID(clClass, "loadClass", 134 | "(Ljava/lang/String;)Ljava/lang/Class;"); 135 | auto entryClassName = env->NewStringUTF("dev.kdrag0n.safetynetfix.EntryPoint"); 136 | auto entryClassObj = env->CallObjectMethod(dexCl, loadClass, entryClassName); 137 | 138 | // Call init. Static initializers don't run when merely calling loadClass from JNI. 139 | LOGD("call init"); 140 | auto entryClass = (jclass) entryClassObj; 141 | auto entryInit = env->GetStaticMethodID(entryClass, "init", "()V"); 142 | env->CallStaticVoidMethod(entryClass, entryInit); 143 | } 144 | }; 145 | 146 | static off_t sendFile(int remote_fd, const std::string& path) { 147 | auto in_fd = open(path.c_str(), O_RDONLY); 148 | if (in_fd < 0) { 149 | LOGE("Failed to open file %s: %d (%s)", path.c_str(), errno, strerror(errno)); 150 | return -1; 151 | } 152 | 153 | auto size = lseek(in_fd, 0, SEEK_END); 154 | if (size < 0) { 155 | LOGERRNO("Failed to get file size"); 156 | close(in_fd); 157 | return -1; 158 | } 159 | lseek(in_fd, 0, SEEK_SET); 160 | 161 | // Send size first for buffer allocation 162 | int ret = write(remote_fd, &size, sizeof(size)); 163 | if (ret < 0) { 164 | LOGERRNO("Failed to send size"); 165 | close(in_fd); 166 | return -1; 167 | } 168 | 169 | ret = sendfile(remote_fd, in_fd, nullptr, size); 170 | if (ret < 0) { 171 | LOGERRNO("Failed to send data"); 172 | close(in_fd); 173 | return -1; 174 | } 175 | 176 | close(in_fd); 177 | return size; 178 | } 179 | 180 | static void companionHandler(int remote_fd) { 181 | // Serve module dex 182 | auto size = sendFile(remote_fd, MODULE_DEX_PATH); 183 | LOGD("Sent module payload: %ld bytes", size); 184 | } 185 | 186 | } 187 | 188 | REGISTER_ZYGISK_COMPANION(safetynetfix::companionHandler) 189 | REGISTER_ZYGISK_MODULE(safetynetfix::SafetyNetFixModule) 190 | -------------------------------------------------------------------------------- /zygisk/module/jni/module.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace safetynetfix { 4 | 5 | static constexpr auto TAG = "SNFix/JNI"; 6 | 7 | static constexpr auto MODULE_DEX_PATH = "/data/adb/modules/safetynet-fix/classes.dex"; 8 | 9 | #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__) 10 | 11 | #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__) 12 | #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__) 13 | #define LOGERRNO(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__ ": %d (%s)", errno, strerror(errno)) 14 | 15 | } 16 | -------------------------------------------------------------------------------- /zygisk/module/jni/zygisk.hpp: -------------------------------------------------------------------------------- 1 | /* Copyright 2022-2023 John "topjohnwu" Wu 2 | * 3 | * Permission to use, copy, modify, and/or distribute this software for any 4 | * purpose with or without fee is hereby granted. 5 | * 6 | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH 7 | * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY 8 | * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, 9 | * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM 10 | * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR 11 | * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR 12 | * PERFORMANCE OF THIS SOFTWARE. 13 | */ 14 | 15 | // This is the public API for Zygisk modules. 16 | // DO NOT MODIFY ANY CODE IN THIS HEADER. 17 | 18 | #pragma once 19 | 20 | #include 21 | 22 | #define ZYGISK_API_VERSION 2 23 | 24 | /* 25 | 26 | *************** 27 | * Introduction 28 | *************** 29 | 30 | On Android, all app processes are forked from a special daemon called "Zygote". 31 | For each new app process, zygote will fork a new process and perform "specialization". 32 | This specialization operation enforces the Android security sandbox on the newly forked 33 | process to make sure that 3rd party application code is only loaded after it is being 34 | restricted within a sandbox. 35 | 36 | On Android, there is also this special process called "system_server". This single 37 | process hosts a significant portion of system services, which controls how the 38 | Android operating system and apps interact with each other. 39 | 40 | The Zygisk framework provides a way to allow developers to build modules and run custom 41 | code before and after system_server and any app processes' specialization. 42 | This enable developers to inject code and alter the behavior of system_server and app processes. 43 | 44 | Please note that modules will only be loaded after zygote has forked the child process. 45 | THIS MEANS ALL OF YOUR CODE RUNS IN THE APP/SYSTEM_SERVER PROCESS, NOT THE ZYGOTE DAEMON! 46 | 47 | ********************* 48 | * Development Guide 49 | ********************* 50 | 51 | Define a class and inherit zygisk::ModuleBase to implement the functionality of your module. 52 | Use the macro REGISTER_ZYGISK_MODULE(className) to register that class to Zygisk. 53 | 54 | Example code: 55 | 56 | static jint (*orig_logger_entry_max)(JNIEnv *env); 57 | static jint my_logger_entry_max(JNIEnv *env) { return orig_logger_entry_max(env); } 58 | 59 | class ExampleModule : public zygisk::ModuleBase { 60 | public: 61 | void onLoad(zygisk::Api *api, JNIEnv *env) override { 62 | this->api = api; 63 | this->env = env; 64 | } 65 | void preAppSpecialize(zygisk::AppSpecializeArgs *args) override { 66 | JNINativeMethod methods[] = { 67 | { "logger_entry_max_payload_native", "()I", (void*) my_logger_entry_max }, 68 | }; 69 | api->hookJniNativeMethods(env, "android/util/Log", methods, 1); 70 | *(void **) &orig_logger_entry_max = methods[0].fnPtr; 71 | } 72 | private: 73 | zygisk::Api *api; 74 | JNIEnv *env; 75 | }; 76 | 77 | REGISTER_ZYGISK_MODULE(ExampleModule) 78 | 79 | ----------------------------------------------------------------------------------------- 80 | 81 | Since your module class's code runs with either Zygote's privilege in pre[XXX]Specialize, 82 | or runs in the sandbox of the target process in post[XXX]Specialize, the code in your class 83 | never runs in a true superuser environment. 84 | 85 | If your module require access to superuser permissions, you can create and register 86 | a root companion handler function. This function runs in a separate root companion 87 | daemon process, and an Unix domain socket is provided to allow you to perform IPC between 88 | your target process and the root companion process. 89 | 90 | Example code: 91 | 92 | static void example_handler(int socket) { ... } 93 | 94 | REGISTER_ZYGISK_COMPANION(example_handler) 95 | 96 | */ 97 | 98 | namespace zygisk { 99 | 100 | struct Api; 101 | struct AppSpecializeArgs; 102 | struct ServerSpecializeArgs; 103 | 104 | class ModuleBase { 105 | public: 106 | 107 | // This method is called as soon as the module is loaded into the target process. 108 | // A Zygisk API handle will be passed as an argument. 109 | virtual void onLoad([[maybe_unused]] Api *api, [[maybe_unused]] JNIEnv *env) {} 110 | 111 | // This method is called before the app process is specialized. 112 | // At this point, the process just got forked from zygote, but no app specific specialization 113 | // is applied. This means that the process does not have any sandbox restrictions and 114 | // still runs with the same privilege of zygote. 115 | // 116 | // All the arguments that will be sent and used for app specialization is passed as a single 117 | // AppSpecializeArgs object. You can read and overwrite these arguments to change how the app 118 | // process will be specialized. 119 | // 120 | // If you need to run some operations as superuser, you can call Api::connectCompanion() to 121 | // get a socket to do IPC calls with a root companion process. 122 | // See Api::connectCompanion() for more info. 123 | virtual void preAppSpecialize([[maybe_unused]] AppSpecializeArgs *args) {} 124 | 125 | // This method is called after the app process is specialized. 126 | // At this point, the process has all sandbox restrictions enabled for this application. 127 | // This means that this method runs with the same privilege of the app's own code. 128 | virtual void postAppSpecialize([[maybe_unused]] const AppSpecializeArgs *args) {} 129 | 130 | // This method is called before the system server process is specialized. 131 | // See preAppSpecialize(args) for more info. 132 | virtual void preServerSpecialize([[maybe_unused]] ServerSpecializeArgs *args) {} 133 | 134 | // This method is called after the system server process is specialized. 135 | // At this point, the process runs with the privilege of system_server. 136 | virtual void postServerSpecialize([[maybe_unused]] const ServerSpecializeArgs *args) {} 137 | }; 138 | 139 | struct AppSpecializeArgs { 140 | // Required arguments. These arguments are guaranteed to exist on all Android versions. 141 | jint &uid; 142 | jint &gid; 143 | jintArray &gids; 144 | jint &runtime_flags; 145 | jint &mount_external; 146 | jstring &se_info; 147 | jstring &nice_name; 148 | jstring &instruction_set; 149 | jstring &app_data_dir; 150 | 151 | // Optional arguments. Please check whether the pointer is null before de-referencing 152 | jboolean *const is_child_zygote; 153 | jboolean *const is_top_app; 154 | jobjectArray *const pkg_data_info_list; 155 | jobjectArray *const whitelisted_data_info_list; 156 | jboolean *const mount_data_dirs; 157 | jboolean *const mount_storage_dirs; 158 | 159 | AppSpecializeArgs() = delete; 160 | }; 161 | 162 | struct ServerSpecializeArgs { 163 | jint &uid; 164 | jint &gid; 165 | jintArray &gids; 166 | jint &runtime_flags; 167 | jlong &permitted_capabilities; 168 | jlong &effective_capabilities; 169 | 170 | ServerSpecializeArgs() = delete; 171 | }; 172 | 173 | namespace internal { 174 | struct api_table; 175 | template void entry_impl(api_table *, JNIEnv *); 176 | } 177 | 178 | // These values are used in Api::setOption(Option) 179 | enum Option : int { 180 | // Force Magisk's denylist unmount routines to run on this process. 181 | // 182 | // Setting this option only makes sense in preAppSpecialize. 183 | // The actual unmounting happens during app process specialization. 184 | // 185 | // Set this option to force all Magisk and modules' files to be unmounted from the 186 | // mount namespace of the process, regardless of the denylist enforcement status. 187 | FORCE_DENYLIST_UNMOUNT = 0, 188 | 189 | // When this option is set, your module's library will be dlclose-ed after post[XXX]Specialize. 190 | // Be aware that after dlclose-ing your module, all of your code will be unmapped from memory. 191 | // YOU MUST NOT ENABLE THIS OPTION AFTER HOOKING ANY FUNCTIONS IN THE PROCESS. 192 | DLCLOSE_MODULE_LIBRARY = 1, 193 | }; 194 | 195 | // Bit masks of the return value of Api::getFlags() 196 | enum StateFlag : uint32_t { 197 | // The user has granted root access to the current process 198 | PROCESS_GRANTED_ROOT = (1u << 0), 199 | 200 | // The current process was added on the denylist 201 | PROCESS_ON_DENYLIST = (1u << 1), 202 | }; 203 | 204 | // All API methods will stop working after post[XXX]Specialize as Zygisk will be unloaded 205 | // from the specialized process afterwards. 206 | struct Api { 207 | 208 | // Connect to a root companion process and get a Unix domain socket for IPC. 209 | // 210 | // This API only works in the pre[XXX]Specialize methods due to SELinux restrictions. 211 | // 212 | // The pre[XXX]Specialize methods run with the same privilege of zygote. 213 | // If you would like to do some operations with superuser permissions, register a handler 214 | // function that would be called in the root process with REGISTER_ZYGISK_COMPANION(func). 215 | // Another good use case for a companion process is that if you want to share some resources 216 | // across multiple processes, hold the resources in the companion process and pass it over. 217 | // 218 | // The root companion process is ABI aware; that is, when calling this method from a 32-bit 219 | // process, you will be connected to a 32-bit companion process, and vice versa for 64-bit. 220 | // 221 | // Returns a file descriptor to a socket that is connected to the socket passed to your 222 | // module's companion request handler. Returns -1 if the connection attempt failed. 223 | int connectCompanion(); 224 | 225 | // Get the file descriptor of the root folder of the current module. 226 | // 227 | // This API only works in the pre[XXX]Specialize methods. 228 | // Accessing the directory returned is only possible in the pre[XXX]Specialize methods 229 | // or in the root companion process (assuming that you sent the fd over the socket). 230 | // Both restrictions are due to SELinux and UID. 231 | // 232 | // Returns -1 if errors occurred. 233 | int getModuleDir(); 234 | 235 | // Set various options for your module. 236 | // Please note that this method accepts one single option at a time. 237 | // Check zygisk::Option for the full list of options available. 238 | void setOption(Option opt); 239 | 240 | // Get information about the current process. 241 | // Returns bitwise-or'd zygisk::StateFlag values. 242 | uint32_t getFlags(); 243 | 244 | // Hook JNI native methods for a class 245 | // 246 | // Lookup all registered JNI native methods and replace it with your own methods. 247 | // The original function pointer will be saved in each JNINativeMethod's fnPtr. 248 | // If no matching class, method name, or signature is found, that specific JNINativeMethod.fnPtr 249 | // will be set to nullptr. 250 | void hookJniNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *methods, int numMethods); 251 | 252 | // Hook functions in the PLT (Procedure Linkage Table) of ELFs loaded in memory. 253 | // 254 | // Parsing /proc/[PID]/maps will give you the memory map of a process. As an example: 255 | // 256 | //
257 | // 56b4346000-56b4347000 r-xp 00002000 fe:00 235 /system/bin/app_process64 258 | // (More details: https://man7.org/linux/man-pages/man5/proc.5.html) 259 | // 260 | // For ELFs loaded in memory with pathname matching `regex`, replace function `symbol` with `newFunc`. 261 | // If `oldFunc` is not nullptr, the original function pointer will be saved to `oldFunc`. 262 | void pltHookRegister(const char *regex, const char *symbol, void *newFunc, void **oldFunc); 263 | 264 | // For ELFs loaded in memory with pathname matching `regex`, exclude hooks registered for `symbol`. 265 | // If `symbol` is nullptr, then all symbols will be excluded. 266 | void pltHookExclude(const char *regex, const char *symbol); 267 | 268 | // Commit all the hooks that was previously registered. 269 | // Returns false if an error occurred. 270 | bool pltHookCommit(); 271 | 272 | private: 273 | internal::api_table *tbl; 274 | template friend void internal::entry_impl(internal::api_table *, JNIEnv *); 275 | }; 276 | 277 | // Register a class as a Zygisk module 278 | 279 | #define REGISTER_ZYGISK_MODULE(clazz) \ 280 | void zygisk_module_entry(zygisk::internal::api_table *table, JNIEnv *env) { \ 281 | zygisk::internal::entry_impl(table, env); \ 282 | } 283 | 284 | // Register a root companion request handler function for your module 285 | // 286 | // The function runs in a superuser daemon process and handles a root companion request from 287 | // your module running in a target process. The function has to accept an integer value, 288 | // which is a Unix domain socket that is connected to the target process. 289 | // See Api::connectCompanion() for more info. 290 | // 291 | // NOTE: the function can run concurrently on multiple threads. 292 | // Be aware of race conditions if you have globally shared resources. 293 | 294 | #define REGISTER_ZYGISK_COMPANION(func) \ 295 | void zygisk_companion_entry(int client) { func(client); } 296 | 297 | /********************************************************* 298 | * The following is internal ABI implementation detail. 299 | * You do not have to understand what it is doing. 300 | *********************************************************/ 301 | 302 | namespace internal { 303 | 304 | struct module_abi { 305 | long api_version; 306 | ModuleBase *impl; 307 | 308 | void (*preAppSpecialize)(ModuleBase *, AppSpecializeArgs *); 309 | void (*postAppSpecialize)(ModuleBase *, const AppSpecializeArgs *); 310 | void (*preServerSpecialize)(ModuleBase *, ServerSpecializeArgs *); 311 | void (*postServerSpecialize)(ModuleBase *, const ServerSpecializeArgs *); 312 | 313 | module_abi(ModuleBase *module) : api_version(ZYGISK_API_VERSION), impl(module) { 314 | preAppSpecialize = [](auto m, auto args) { m->preAppSpecialize(args); }; 315 | postAppSpecialize = [](auto m, auto args) { m->postAppSpecialize(args); }; 316 | preServerSpecialize = [](auto m, auto args) { m->preServerSpecialize(args); }; 317 | postServerSpecialize = [](auto m, auto args) { m->postServerSpecialize(args); }; 318 | } 319 | }; 320 | 321 | struct api_table { 322 | // Base 323 | void *impl; 324 | bool (*registerModule)(api_table *, module_abi *); 325 | 326 | void (*hookJniNativeMethods)(JNIEnv *, const char *, JNINativeMethod *, int); 327 | void (*pltHookRegister)(const char *, const char *, void *, void **); 328 | void (*pltHookExclude)(const char *, const char *); 329 | bool (*pltHookCommit)(); 330 | int (*connectCompanion)(void * /* impl */); 331 | void (*setOption)(void * /* impl */, Option); 332 | int (*getModuleDir)(void * /* impl */); 333 | uint32_t (*getFlags)(void * /* impl */); 334 | }; 335 | 336 | template 337 | void entry_impl(api_table *table, JNIEnv *env) { 338 | static Api api; 339 | api.tbl = table; 340 | static T module; 341 | ModuleBase *m = &module; 342 | static module_abi abi(m); 343 | if (!table->registerModule(table, &abi)) return; 344 | m->onLoad(&api, env); 345 | } 346 | 347 | } // namespace internal 348 | 349 | inline int Api::connectCompanion() { 350 | return tbl->connectCompanion ? tbl->connectCompanion(tbl->impl) : -1; 351 | } 352 | inline int Api::getModuleDir() { 353 | return tbl->getModuleDir ? tbl->getModuleDir(tbl->impl) : -1; 354 | } 355 | inline void Api::setOption(Option opt) { 356 | if (tbl->setOption) tbl->setOption(tbl->impl, opt); 357 | } 358 | inline uint32_t Api::getFlags() { 359 | return tbl->getFlags ? tbl->getFlags(tbl->impl) : 0; 360 | } 361 | inline void Api::hookJniNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *methods, int numMethods) { 362 | if (tbl->hookJniNativeMethods) tbl->hookJniNativeMethods(env, className, methods, numMethods); 363 | } 364 | inline void Api::pltHookRegister(const char *regex, const char *symbol, void *newFunc, void **oldFunc) { 365 | if (tbl->pltHookRegister) tbl->pltHookRegister(regex, symbol, newFunc, oldFunc); 366 | } 367 | inline void Api::pltHookExclude(const char *regex, const char *symbol) { 368 | if (tbl->pltHookExclude) tbl->pltHookExclude(regex, symbol); 369 | } 370 | inline bool Api::pltHookCommit() { 371 | return tbl->pltHookCommit != nullptr && tbl->pltHookCommit(); 372 | } 373 | 374 | } // namespace zygisk 375 | 376 | extern "C" { 377 | 378 | [[gnu::visibility("default"), maybe_unused]] 379 | void zygisk_module_entry(zygisk::internal::api_table *, JNIEnv *); 380 | 381 | [[gnu::visibility("default"), maybe_unused]] 382 | void zygisk_companion_entry(int); 383 | 384 | } // extern "C" 385 | -------------------------------------------------------------------------------- /zygisk/module/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /zygisk/settings.gradle: -------------------------------------------------------------------------------- 1 | dependencyResolutionManagement { 2 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 3 | repositories { 4 | google() 5 | mavenCentral() 6 | } 7 | } 8 | include ':module' 9 | --------------------------------------------------------------------------------