├── .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
└── uninstall.sh
├── update.json
└── zygisk
└── module
├── .gitignore
└── jni
├── Android.mk
├── Application.mk
├── module.cpp
├── module.h
└── zygisk.hpp
/.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 of SafetyNet & Play Integrity API tests result**
29 | Testing SafetyNet: https://play.google.com/store/apps/details?id=rikka.safetynetchecker
30 | Testing Play Integrity API: https://play.google.com/store/apps/details?id=gr.nikolasspyr.integritycheck
31 |
32 | **Device info**
33 | Device model:
34 | Android version:
35 | ROM name/version:
36 |
37 | **Logs**
38 | Connect your phone to a computer and run `adb logcat > issue.log` then run SafetyNet & Play Integrity API tests. Stop log by `Ctrl + C` combination. Attach the log file to this issue.
39 |
40 | **Additional context**
41 | Add any other context about the problem here.
42 |
43 | **Checklist**
44 | - [ ] I confirm that the SELinux status is `Enforcing` on my device.
45 | - [ ] All information is present
46 | - [ ] Screenshots are attached
47 | - [ ] Logs are attached
48 |
--------------------------------------------------------------------------------
/.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-MOD_2.0
2 | * Fix KernelSU support. You still need "ZygiskOnKernelSU".
3 | * Fix WiFi calling on some devices (and maybe other related issues) by moving changing *ro.product.first_api_level* from global namespace to GMS only.
4 | * Pass *MEETS_STRONG_INTEGRITY*. By default you need device that launched with Android 13+ or custom ROM that manipulate with *ro.product.first_api_level* (>= 33 / or `null` / or not present).
If you want to play with it more complex - use separate "-STRONG" build. NOTE: Various system issues are possible on "-STRONG" build!
5 |
6 | ## v2.4.0-MOD_1.3
7 |
8 | * Fix "stat /sys/fs/selinux" access time reading. Also removed archaic MIUI cross-region shenanigans. Thanks to PR by aviraxp!
9 | * Ignore props changing on Xiaomi.eu. This fixes randomly attestation failings. So strange ROM...
10 | * Added Riru version back. Remember that is need old MagiskHide support (and adding com.google.android.gms/com.google.android.gms.unstable to HideList) !
11 | * Added microG version. Note there is some strange behavior that GMS can crash while run SN attest more than 2 times in one session. Just do not do this. This behavior should not affect applications in real life.
12 |
13 | ## v2.4.0-MOD_1.2
14 |
15 | * Fix crash and endless tests loop/failing on Android < 9.0 (bug from original version 2.4.0).
16 | * Do not unpatch (revert) changes. To prevent possible tests failing after a while on some ROMs (cross conflicts).
17 |
18 | ## v2.4.0-MOD_1.1
19 |
20 | * Fix KeyStore hook desynchronization (tests randomly failing problem).
21 |
22 | ## v2.4.0-MOD_1.0
23 |
24 | * It is now based on top of original v2.4.0 codebase instead of v2.3.1, with adding new hiding algorithm for current realities and some code refreshing.
25 |
--------------------------------------------------------------------------------
/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 & Play Integrity Fix [MOD]
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 [MOD] version](https://github.com/Displax/safetynet-fix/releases)**
14 |
15 | Install the downloaded module in Magisk Manager, then **enable Zygisk in Magisk settings.**
16 |
17 | ## How does it work?
18 |
19 | See [Details](docs/details.md) for details about how this module works.
20 |
21 | ## ROM integration
22 |
23 | 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.
24 |
--------------------------------------------------------------------------------
/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 34
10 |
11 | defaultConfig {
12 | applicationId "dev.kdrag0n.safetynetfix"
13 | minSdk 24
14 | targetSdk 34
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 |
29 | compileOptions {
30 | sourceCompatibility JavaVersion.VERSION_1_8
31 | targetCompatibility JavaVersion.VERSION_1_8
32 | }
33 |
34 | kotlinOptions {
35 | jvmTarget = '1.8'
36 | }
37 | }
38 |
39 | dependencies {
40 | implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.9.0'
41 | }
42 |
--------------------------------------------------------------------------------
/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 isCallerSafetyNet() = Thread.currentThread().stackTrace.any {
25 | // a.a.engineGetCertificateChain(Unknown Source:15)
26 | // java.security.KeyStore.getCertificateChain(KeyStore.java:1087)
27 | // com.google.ccc.abuse.droidguard.DroidGuard.initNative(Native Method)
28 | // com.google.ccc.abuse.droidguard.DroidGuard.init(DroidGuard.java:447)
29 | // java.lang.reflect.Method.invoke(Native Method)
30 | // xvq.b(:com.google.android.gms@212621053@21.26.21 (190400-387928701):1)
31 | // xuc.a(:com.google.android.gms@212621053@21.26.21 (190400-387928701):5)
32 | // xuc.eX(:com.google.android.gms@212621053@21.26.21 (190400-387928701):1)
33 | // dzx.onTransact(:com.google.android.gms@212621053@21.26.21 (190400-387928701):8)
34 | // android.os.Binder.execTransactInternal(Binder.java:1179)
35 | // android.os.Binder.execTransact(Binder.java:1143)
36 | logDebug("Stack trace element: $it")
37 | it.className.contains("DroidGuard", ignoreCase = true)
38 | }
39 |
40 | override fun engineGetCertificateChain(alias: String?): Array? {
41 | logDebug("Proxy key store: get certificate chain")
42 |
43 | if (isCallerSafetyNet()) {
44 | logDebug("Blocking call")
45 | throw UnsupportedOperationException()
46 | } else {
47 | logDebug("Allowing call")
48 | return orig.engineGetCertificateChain(alias)
49 | }
50 | }
51 |
52 | // Direct delegation. We have to do this manually because the Kotlin compiler can only do it
53 | // for interfaces, not abstract classes.
54 | override fun engineGetKey(alias: String?, password: CharArray?): Key? = orig.engineGetKey(alias, password)
55 | override fun engineGetCertificate(alias: String?): Certificate? = orig.engineGetCertificate(alias)
56 | override fun engineGetCreationDate(alias: String?): Date? = orig.engineGetCreationDate(alias)
57 | override fun engineSetKeyEntry(alias: String?, key: Key?, password: CharArray?, chain: Array?) = orig.engineSetKeyEntry(alias, key, password, chain)
58 | override fun engineSetKeyEntry(alias: String?, key: ByteArray?, chain: Array?) = orig.engineSetKeyEntry(alias, key, chain)
59 | override fun engineSetCertificateEntry(alias: String?, cert: Certificate?) = orig.engineSetCertificateEntry(alias, cert)
60 | override fun engineDeleteEntry(alias: String?) = orig.engineDeleteEntry(alias)
61 | override fun engineAliases(): Enumeration? = orig.engineAliases()
62 | override fun engineContainsAlias(alias: String?) = orig.engineContainsAlias(alias)
63 | override fun engineSize() = orig.engineSize()
64 | override fun engineIsKeyEntry(alias: String?) = orig.engineIsKeyEntry(alias)
65 | override fun engineIsCertificateEntry(alias: String?) = orig.engineIsCertificateEntry(alias)
66 | override fun engineGetCertificateAlias(cert: Certificate?): String? = orig.engineGetCertificateAlias(cert)
67 | override fun engineStore(stream: OutputStream?, password: CharArray?) = orig.engineStore(stream, password)
68 | override fun engineLoad(stream: InputStream?, password: CharArray?) = orig.engineLoad(stream, password)
69 |
70 | companion object {
71 | @Volatile internal var androidImpl: KeyStoreSpi? = null
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/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" && Build.HOST != "xiaomi.eu") {
25 |
26 | val patchedProduct = /* ro.product.name */ "marlin"
27 | val patchedDevice = /* ro.product.device */ "marlin"
28 | val patchedModel = /* ro.product.model */ "Pixel XL"
29 | val patchedFingerprint = /* ro.build.fingerprint */ "google/marlin/marlin:7.1.2/NJH47F/4146041:user/release-keys"
30 |
31 | logDebug("Patch PRODUCT prop. Set it to: $patchedProduct")
32 | Build::class.java.getDeclaredField("PRODUCT").let { field ->
33 | field.isAccessible = true
34 | field.set(null, patchedProduct)
35 | }
36 | logDebug("Patch DEVICE prop. Set it to: $patchedDevice")
37 | Build::class.java.getDeclaredField("DEVICE").let { field ->
38 | field.isAccessible = true
39 | field.set(null, patchedDevice)
40 | }
41 | logDebug("Patch MODEL prop. Set it to: $patchedModel")
42 | Build::class.java.getDeclaredField("MODEL").let { field ->
43 | field.isAccessible = true
44 | field.set(null, patchedModel)
45 | }
46 | logDebug("Patch FINGERPRINT prop. Set it to: $patchedFingerprint")
47 | Build::class.java.getDeclaredField("FINGERPRINT").let { field ->
48 | field.isAccessible = true
49 | field.set(null, patchedFingerprint)
50 | }
51 | }
52 | return super.getService(type, algorithm)
53 | }
54 |
55 | override fun getServices(): MutableSet? {
56 | logDebug("Get services")
57 | return super.getServices()
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/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:8.2.0-alpha15"
9 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.0"
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/Displax/safetynet-fix/67d1d1b86e145a8ddcd2f023ac878dc6d23ee3db/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-8.2.1-bin.zip
4 | networkTimeout=10000
5 | validateDistributionUrl=true
6 | zipStoreBase=GRADLE_USER_HOME
7 | zipStorePath=wrapper/dists
8 |
--------------------------------------------------------------------------------
/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 | # Use the maximum available, or set MAX_FD != -1 to use that value.
89 | MAX_FD=maximum
90 |
91 | warn () {
92 | echo "$*"
93 | } >&2
94 |
95 | die () {
96 | echo
97 | echo "$*"
98 | echo
99 | exit 1
100 | } >&2
101 |
102 | # OS specific support (must be 'true' or 'false').
103 | cygwin=false
104 | msys=false
105 | darwin=false
106 | nonstop=false
107 | case "$( uname )" in #(
108 | CYGWIN* ) cygwin=true ;; #(
109 | Darwin* ) darwin=true ;; #(
110 | MSYS* | MINGW* ) msys=true ;; #(
111 | NONSTOP* ) nonstop=true ;;
112 | esac
113 |
114 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
115 |
116 |
117 | # Determine the Java command to use to start the JVM.
118 | if [ -n "$JAVA_HOME" ] ; then
119 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
120 | # IBM's JDK on AIX uses strange locations for the executables
121 | JAVACMD=$JAVA_HOME/jre/sh/java
122 | else
123 | JAVACMD=$JAVA_HOME/bin/java
124 | fi
125 | if [ ! -x "$JAVACMD" ] ; then
126 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
127 |
128 | Please set the JAVA_HOME variable in your environment to match the
129 | location of your Java installation."
130 | fi
131 | else
132 | JAVACMD=java
133 | if ! command -v java >/dev/null 2>&1
134 | then
135 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
136 |
137 | Please set the JAVA_HOME variable in your environment to match the
138 | location of your Java installation."
139 | fi
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 |
201 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
202 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
203 |
204 | # Collect all arguments for the java command;
205 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
206 | # shell script including quotes and variable substitutions, so put them in
207 | # double quotes to make sure that they get re-expanded; and
208 | # * put everything else in single quotes, so that it's not re-expanded.
209 |
210 | set -- \
211 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
212 | -classpath "$CLASSPATH" \
213 | org.gradle.wrapper.GradleWrapperMain \
214 | "$@"
215 |
216 | # Stop when "xargs" is not available.
217 | if ! command -v xargs >/dev/null 2>&1
218 | then
219 | die "xargs is not available"
220 | fi
221 |
222 | # Use "xargs" to parse quoted args.
223 | #
224 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
225 | #
226 | # In Bash we could simply go:
227 | #
228 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
229 | # set -- "${ARGS[@]}" "$@"
230 | #
231 | # but POSIX shell has neither arrays nor command substitution, so instead we
232 | # post-process each arg (as a line of input to sed) to backslash-escape any
233 | # character that might be a shell metacharacter, then use eval to reverse
234 | # that process (while maintaining the separation between arguments), and wrap
235 | # the whole thing up as a single "set" statement.
236 | #
237 | # This will of course break if any of these variables contains a newline or
238 | # an unmatched quote.
239 | #
240 |
241 | eval "set -- $(
242 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
243 | xargs -n1 |
244 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
245 | tr '\n' ' '
246 | )" '"$@"'
247 |
248 | exec "$JAVACMD" "$@"
249 |
--------------------------------------------------------------------------------
/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 | if $BOOTMODE; then
2 | ui_print "- Installing from Magisk / KernelSU app"
3 | else
4 | ui_print "*********************************************************"
5 | ui_print "! Install from recovery is NOT supported"
6 | ui_print "! Recovery sucks"
7 | ui_print "! Please install from Magisk / KernelSU app"
8 | abort "*********************************************************"
9 | fi
10 |
11 | mv -f "$MODPATH/SNFix.dex" "/data/adb/"
12 |
13 | # Android < 8.0 | No Zygisk
14 | if [ "$API" -lt 26 ]; then
15 | ui_print "*********************************************************"
16 | ui_print "! Functionality is limited on Android 7 and older"
17 | ui_print "! Hardware-backed attestation will not be disabled"
18 | ui_print "! MODEL & FINGERPRINT props will not be modified"
19 | ui_print "*********************************************************"
20 |
21 | # Remove Zygisk part but keep props and scripts
22 | rm -rf "$MODPATH/zygisk"
23 | rm -rf "/data/adb/SNFix.dex"
24 | fi
25 |
--------------------------------------------------------------------------------
/magisk/module.prop:
--------------------------------------------------------------------------------
1 | id=safetynet-fix
2 | name=Universal SafetyNet Fix
3 | version=v2.4.0-MOD_2.0
4 | versionCode=24020
5 | author=kdrag0n, modded by Displax
6 | description=A universal fix for SafetyNet and Play Integrity API on Android 8–13 devices with hardware attestation.
7 | updateJson=https://raw.githubusercontent.com/Displax/safetynet-fix/dev/update.json
8 |
--------------------------------------------------------------------------------
/magisk/post-fs-data.sh:
--------------------------------------------------------------------------------
1 | # Remove Play Services from the Magisk Denylist when set to enforcing.
2 | if magisk --denylist status; then
3 | magisk --denylist rm com.google.android.gms
4 | fi
5 |
--------------------------------------------------------------------------------
/magisk/service.sh:
--------------------------------------------------------------------------------
1 | # Sensitive properties
2 |
3 | maybe_set_prop() {
4 | local prop="$1"
5 | local contains="$2"
6 | local value="$3"
7 |
8 | if [[ "$(getprop "$prop")" == *"$contains"* ]]; then
9 | resetprop "$prop" "$value"
10 | fi
11 | }
12 |
13 | # Magisk recovery mode
14 | maybe_set_prop ro.bootmode recovery unknown
15 | maybe_set_prop ro.boot.mode recovery unknown
16 | maybe_set_prop vendor.boot.mode recovery unknown
17 |
18 | # Hiding SELinux | Permissive status
19 | resetprop --delete ro.build.selinux
20 |
21 | # Hiding SELinux | Use toybox to protect *stat* access time reading
22 | if [[ "$(toybox cat /sys/fs/selinux/enforce)" == "0" ]]; then
23 | chmod 640 /sys/fs/selinux/enforce
24 | chmod 440 /sys/fs/selinux/policy
25 | fi
26 |
27 | # Late props which must be set after boot_completed
28 | {
29 | until [[ "$(getprop sys.boot_completed)" == "1" ]]; do
30 | sleep 1
31 | done
32 |
33 | # SafetyNet/Play Integrity | Avoid breaking Realme fingerprint scanners
34 | resetprop ro.boot.flash.locked 1
35 |
36 | # SafetyNet/Play Integrity | Avoid breaking Oppo fingerprint scanners
37 | resetprop ro.boot.vbmeta.device_state locked
38 |
39 | # SafetyNet/Play Integrity | Avoid breaking OnePlus display modes/fingerprint scanners
40 | resetprop vendor.boot.verifiedbootstate green
41 |
42 | # SafetyNet/Play Integrity | Avoid breaking OnePlus display modes/fingerprint scanners on OOS 12
43 | resetprop ro.boot.verifiedbootstate green
44 | resetprop ro.boot.veritymode enforcing
45 | resetprop vendor.boot.vbmeta.device_state locked
46 | }&
47 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/magisk/uninstall.sh:
--------------------------------------------------------------------------------
1 | rm -rf "/data/adb/SNFix.dex"
2 |
--------------------------------------------------------------------------------
/update.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "v2.4.0-MOD_2.0",
3 | "versionCode": 24020,
4 | "zipUrl": "https://github.com/Displax/safetynet-fix/releases/download/v2.4.0-MOD_2.0/safetynet-fix-v2.4.0-MOD_2.0.zip",
5 | "changelog": "https://raw.githubusercontent.com/Displax/safetynet-fix/dev/CHANGELOG.md"
6 | }
7 |
--------------------------------------------------------------------------------
/zygisk/module/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 | /libs
3 | /obj
4 |
--------------------------------------------------------------------------------
/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 | // Only touch GMS
88 | if (process.rfind("com.google.android.gms", 0) != 0) {
89 | api->setOption(zygisk::DLCLOSE_MODULE_LIBRARY);
90 | return;
91 | }
92 |
93 | // Force DenyList unmounting for all GMS processes
94 | api->setOption(zygisk::FORCE_DENYLIST_UNMOUNT);
95 |
96 | // The unstable process is where SafetyNet attestation actually runs, so we only need to
97 | // spoof the model in that process. Leaving other processes alone fixes various issues
98 | // caused by model detection and flag provisioning, such as broken weather with the new
99 | // smartspace on Android 12.
100 | if (process == "com.google.android.gms.unstable") {
101 | // Load the payload, but don't inject it yet until after specialization
102 | // Otherwise, specialization fails if any code from the payload still happens to be
103 | // running
104 | LOGD("Loading payload...");
105 | loadPayload();
106 | LOGD("Payload loaded");
107 | }
108 | }
109 |
110 | void injectPayload() {
111 | // First, get the system classloader
112 | LOGD("get system classloader");
113 | auto clClass = env->FindClass("java/lang/ClassLoader");
114 | auto getSystemClassLoader = env->GetStaticMethodID(clClass, "getSystemClassLoader",
115 | "()Ljava/lang/ClassLoader;");
116 | auto systemClassLoader = env->CallStaticObjectMethod(clClass, getSystemClassLoader);
117 |
118 | // Assuming we have a valid mapped module, load it. This is similar to the approach used for
119 | // Dynamite modules in GmsCompat, except we can use InMemoryDexClassLoader directly instead of
120 | // tampering with DelegateLastClassLoader's DexPathList.
121 | LOGD("create buffer");
122 | auto buf = env->NewDirectByteBuffer(moduleDex.data(), moduleDex.size());
123 | LOGD("create class loader");
124 | auto dexClClass = env->FindClass("dalvik/system/InMemoryDexClassLoader");
125 | auto dexClInit = env->GetMethodID(dexClClass, "",
126 | "(Ljava/nio/ByteBuffer;Ljava/lang/ClassLoader;)V");
127 | auto dexCl = env->NewObject(dexClClass, dexClInit, buf, systemClassLoader);
128 |
129 | // Load the class
130 | LOGD("load class");
131 | auto loadClass = env->GetMethodID(clClass, "loadClass",
132 | "(Ljava/lang/String;)Ljava/lang/Class;");
133 | auto entryClassName = env->NewStringUTF("dev.kdrag0n.safetynetfix.EntryPoint");
134 | auto entryClassObj = env->CallObjectMethod(dexCl, loadClass, entryClassName);
135 |
136 | // Call init. Static initializers don't run when merely calling loadClass from JNI.
137 | LOGD("call init");
138 | auto entryClass = (jclass) entryClassObj;
139 | auto entryInit = env->GetStaticMethodID(entryClass, "init", "()V");
140 | env->CallStaticVoidMethod(entryClass, entryInit);
141 | }
142 | };
143 |
144 | static off_t sendFile(int remote_fd, const std::string& path) {
145 | auto in_fd = open(path.c_str(), O_RDONLY);
146 | if (in_fd < 0) {
147 | LOGE("Failed to open file %s: %d (%s)", path.c_str(), errno, strerror(errno));
148 | return -1;
149 | }
150 |
151 | auto size = lseek(in_fd, 0, SEEK_END);
152 | if (size < 0) {
153 | LOGERRNO("Failed to get file size");
154 | close(in_fd);
155 | return -1;
156 | }
157 | lseek(in_fd, 0, SEEK_SET);
158 |
159 | // Send size first for buffer allocation
160 | int ret = write(remote_fd, &size, sizeof(size));
161 | if (ret < 0) {
162 | LOGERRNO("Failed to send size");
163 | close(in_fd);
164 | return -1;
165 | }
166 |
167 | ret = sendfile(remote_fd, in_fd, nullptr, size);
168 | if (ret < 0) {
169 | LOGERRNO("Failed to send data");
170 | close(in_fd);
171 | return -1;
172 | }
173 |
174 | close(in_fd);
175 | return size;
176 | }
177 |
178 | static void companionHandler(int remote_fd) {
179 | // Serve module dex
180 | auto size = sendFile(remote_fd, MODULE_DEX_PATH);
181 | LOGD("Sent module payload: %ld bytes", size);
182 | }
183 |
184 | }
185 |
186 | REGISTER_ZYGISK_COMPANION(safetynetfix::companionHandler)
187 | REGISTER_ZYGISK_MODULE(safetynetfix::SafetyNetFixModule)
188 |
--------------------------------------------------------------------------------
/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/SNFix.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 | // This is the public API for Zygisk modules.
2 | // DO NOT MODIFY ANY CODE IN THIS HEADER.
3 |
4 | #pragma once
5 |
6 | #include
7 |
8 | #define ZYGISK_API_VERSION 1
9 |
10 | /*
11 |
12 | Define a class and inherit zygisk::ModuleBase to implement the functionality of your module.
13 | Use the macro REGISTER_ZYGISK_MODULE(className) to register that class to Zygisk.
14 |
15 | Please note that modules will only be loaded after zygote has forked the child process.
16 | THIS MEANS ALL OF YOUR CODE RUNS IN THE APP/SYSTEM SERVER PROCESS, NOT THE ZYGOTE DAEMON!
17 |
18 | Example code:
19 |
20 | static jint (*orig_logger_entry_max)(JNIEnv *env);
21 | static jint my_logger_entry_max(JNIEnv *env) { return orig_logger_entry_max(env); }
22 |
23 | static void example_handler(int socket) { ... }
24 |
25 | class ExampleModule : public zygisk::ModuleBase {
26 | public:
27 | void onLoad(zygisk::Api *api, JNIEnv *env) override {
28 | this->api = api;
29 | this->env = env;
30 | }
31 | void preAppSpecialize(zygisk::AppSpecializeArgs *args) override {
32 | JNINativeMethod methods[] = {
33 | { "logger_entry_max_payload_native", "()I", (void*) my_logger_entry_max },
34 | };
35 | api->hookJniNativeMethods(env, "android/util/Log", methods, 1);
36 | *(void **) &orig_logger_entry_max = methods[0].fnPtr;
37 | }
38 | private:
39 | zygisk::Api *api;
40 | JNIEnv *env;
41 | };
42 |
43 | REGISTER_ZYGISK_MODULE(ExampleModule)
44 |
45 | REGISTER_ZYGISK_COMPANION(example_handler)
46 |
47 | */
48 |
49 | namespace zygisk {
50 |
51 | struct Api;
52 | struct AppSpecializeArgs;
53 | struct ServerSpecializeArgs;
54 |
55 | class ModuleBase {
56 | public:
57 |
58 | // This function is called when the module is loaded into the target process.
59 | // A Zygisk API handle will be sent as an argument; call utility functions or interface
60 | // with Zygisk through this handle.
61 | virtual void onLoad(Api *api, JNIEnv *env) {}
62 |
63 | // This function is called before the app process is specialized.
64 | // At this point, the process just got forked from zygote, but no app specific specialization
65 | // is applied. This means that the process does not have any sandbox restrictions and
66 | // still runs with the same privilege of zygote.
67 | //
68 | // All the arguments that will be sent and used for app specialization is passed as a single
69 | // AppSpecializeArgs object. You can read and overwrite these arguments to change how the app
70 | // process will be specialized.
71 | //
72 | // If you need to run some operations as superuser, you can call Api::connectCompanion() to
73 | // get a socket to do IPC calls with a root companion process.
74 | // See Api::connectCompanion() for more info.
75 | virtual void preAppSpecialize(AppSpecializeArgs *args) {}
76 |
77 | // This function is called after the app process is specialized.
78 | // At this point, the process has all sandbox restrictions enabled for this application.
79 | // This means that this function runs as the same privilege of the app's own code.
80 | virtual void postAppSpecialize(const AppSpecializeArgs *args) {}
81 |
82 | // This function is called before the system server process is specialized.
83 | // See preAppSpecialize(args) for more info.
84 | virtual void preServerSpecialize(ServerSpecializeArgs *args) {}
85 |
86 | // This function is called after the system server process is specialized.
87 | // At this point, the process runs with the privilege of system_server.
88 | virtual void postServerSpecialize(const ServerSpecializeArgs *args) {}
89 | };
90 |
91 | struct AppSpecializeArgs {
92 | // Required arguments. These arguments are guaranteed to exist on all Android versions.
93 | jint &uid;
94 | jint &gid;
95 | jintArray &gids;
96 | jint &runtime_flags;
97 | jint &mount_external;
98 | jstring &se_info;
99 | jstring &nice_name;
100 | jstring &instruction_set;
101 | jstring &app_data_dir;
102 |
103 | // Optional arguments. Please check whether the pointer is null before de-referencing
104 | jboolean *const is_child_zygote;
105 | jboolean *const is_top_app;
106 | jobjectArray *const pkg_data_info_list;
107 | jobjectArray *const whitelisted_data_info_list;
108 | jboolean *const mount_data_dirs;
109 | jboolean *const mount_storage_dirs;
110 |
111 | AppSpecializeArgs() = delete;
112 | };
113 |
114 | struct ServerSpecializeArgs {
115 | jint &uid;
116 | jint &gid;
117 | jintArray &gids;
118 | jint &runtime_flags;
119 | jlong &permitted_capabilities;
120 | jlong &effective_capabilities;
121 |
122 | ServerSpecializeArgs() = delete;
123 | };
124 |
125 | namespace internal {
126 | struct api_table;
127 | template void entry_impl(api_table *, JNIEnv *);
128 | }
129 |
130 | // These values are used in Api::setOption(Option)
131 | enum Option : int {
132 | // Force Magisk's denylist unmount routines to run on this process.
133 | //
134 | // Setting this option only makes sense in preAppSpecialize.
135 | // The actual unmounting happens during app process specialization.
136 | //
137 | // Processes added to Magisk's denylist will have all Magisk and its modules' files unmounted
138 | // from its mount namespace. In addition, all Zygisk code will be unloaded from memory, which
139 | // also implies that no Zygisk modules (including yours) are loaded.
140 | //
141 | // However, if for any reason your module still wants the unmount part of the denylist
142 | // operation to be enabled EVEN IF THE PROCESS IS NOT ON THE DENYLIST, set this option.
143 | FORCE_DENYLIST_UNMOUNT = 0,
144 |
145 | // When this option is set, your module's library will be dlclose-ed after post[XXX]Specialize.
146 | // Be aware that after dlclose-ing your module, all of your code will be unmapped.
147 | // YOU SHOULD NOT ENABLE THIS OPTION AFTER HOOKING ANY FUNCTION IN THE PROCESS.
148 | DLCLOSE_MODULE_LIBRARY = 1,
149 | };
150 |
151 | struct Api {
152 |
153 | // Connect to a root companion process and get a Unix domain socket for IPC.
154 | //
155 | // This API only works in the pre[XXX]Specialize functions due to SELinux restrictions.
156 | //
157 | // The pre[XXX]Specialize functions run with the same privilege of zygote.
158 | // If you would like to do some operations with superuser permissions, register a handler
159 | // function that would be called in the root process with REGISTER_ZYGISK_COMPANION(func).
160 | // Another good use case for a companion process is that if you want to share some resources
161 | // across multiple processes, hold the resources in the companion process and pass it over.
162 | //
163 | // Returns a file descriptor to a socket that is connected to the socket passed to your
164 | // module's companion request handler. Returns -1 if the connection attempt failed.
165 | int connectCompanion();
166 |
167 | // Set various options for your module.
168 | // Please note that this function accepts one single option at a time.
169 | // Check zygisk::Option for the full list of options available.
170 | void setOption(Option opt);
171 |
172 | // Hook JNI native methods for a class
173 | //
174 | // Lookup all registered JNI native methods and replace it with your own functions.
175 | // The original function pointer will be saved in each JNINativeMethod's fnPtr.
176 | // If no matching class, method name, or signature is found, that specific JNINativeMethod.fnPtr
177 | // will be set to nullptr.
178 | void hookJniNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *methods, int numMethods);
179 |
180 | // For ELFs loaded in memory matching `regex`, replace function `symbol` with `newFunc`.
181 | // If `oldFunc` is not nullptr, the original function pointer will be saved to `oldFunc`.
182 | void pltHookRegister(const char *regex, const char *symbol, void *newFunc, void **oldFunc);
183 |
184 | // For ELFs loaded in memory matching `regex`, exclude hooks registered for `symbol`.
185 | // If `symbol` is nullptr, then all symbols will be excluded.
186 | void pltHookExclude(const char *regex, const char *symbol);
187 |
188 | // Commit all the hooks that was previously registered.
189 | // Returns false if an error occurred.
190 | bool pltHookCommit();
191 |
192 | private:
193 | internal::api_table *impl;
194 | template friend void internal::entry_impl(internal::api_table *, JNIEnv *);
195 | };
196 |
197 | // Register a class as a Zygisk module
198 |
199 | #define REGISTER_ZYGISK_MODULE(clazz) \
200 | void zygisk_module_entry(zygisk::internal::api_table *table, JNIEnv *env) { \
201 | zygisk::internal::entry_impl(table, env); \
202 | }
203 |
204 | // Register a root companion request handler function for your module
205 | //
206 | // The function runs in a superuser daemon process and handles a root companion request from
207 | // your module running in a target process. The function has to accept an integer value,
208 | // which is a socket that is connected to the target process.
209 | // See Api::connectCompanion() for more info.
210 | //
211 | // NOTE: the function can run concurrently on multiple threads.
212 | // Be aware of race conditions if you have a globally shared resource.
213 |
214 | #define REGISTER_ZYGISK_COMPANION(func) \
215 | void zygisk_companion_entry(int client) { func(client); }
216 |
217 | /************************************************************************************
218 | * All the code after this point is internal code used to interface with Zygisk
219 | * and guarantee ABI stability. You do not have to understand what it is doing.
220 | ************************************************************************************/
221 |
222 | namespace internal {
223 |
224 | struct module_abi {
225 | long api_version;
226 | ModuleBase *_this;
227 |
228 | void (*preAppSpecialize)(ModuleBase *, AppSpecializeArgs *);
229 | void (*postAppSpecialize)(ModuleBase *, const AppSpecializeArgs *);
230 | void (*preServerSpecialize)(ModuleBase *, ServerSpecializeArgs *);
231 | void (*postServerSpecialize)(ModuleBase *, const ServerSpecializeArgs *);
232 |
233 | module_abi(ModuleBase *module) : api_version(ZYGISK_API_VERSION), _this(module) {
234 | preAppSpecialize = [](auto self, auto args) { self->preAppSpecialize(args); };
235 | postAppSpecialize = [](auto self, auto args) { self->postAppSpecialize(args); };
236 | preServerSpecialize = [](auto self, auto args) { self->preServerSpecialize(args); };
237 | postServerSpecialize = [](auto self, auto args) { self->postServerSpecialize(args); };
238 | }
239 | };
240 |
241 | struct api_table {
242 | // These first 2 entries are permanent, shall never change
243 | void *_this;
244 | bool (*registerModule)(api_table *, module_abi *);
245 |
246 | // Utility functions
247 | void (*hookJniNativeMethods)(JNIEnv *, const char *, JNINativeMethod *, int);
248 | void (*pltHookRegister)(const char *, const char *, void *, void **);
249 | void (*pltHookExclude)(const char *, const char *);
250 | bool (*pltHookCommit)();
251 |
252 | // Zygisk functions
253 | int (*connectCompanion)(void * /* _this */);
254 | void (*setOption)(void * /* _this */, Option);
255 | };
256 |
257 | template
258 | void entry_impl(api_table *table, JNIEnv *env) {
259 | ModuleBase *module = new T();
260 | if (!table->registerModule(table, new module_abi(module)))
261 | return;
262 | auto api = new Api();
263 | api->impl = table;
264 | module->onLoad(api, env);
265 | }
266 |
267 | } // namespace internal
268 |
269 | int Api::connectCompanion() {
270 | return impl->connectCompanion(impl->_this);
271 | }
272 | void Api::setOption(Option opt) {
273 | impl->setOption(impl->_this, opt);
274 | }
275 | void Api::hookJniNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *methods, int numMethods) {
276 | impl->hookJniNativeMethods(env, className, methods, numMethods);
277 | }
278 | void Api::pltHookRegister(const char *regex, const char *symbol, void *newFunc, void **oldFunc) {
279 | impl->pltHookRegister(regex, symbol, newFunc, oldFunc);
280 | }
281 | void Api::pltHookExclude(const char *regex, const char *symbol) {
282 | impl->pltHookExclude(regex, symbol);
283 | }
284 | bool Api::pltHookCommit() {
285 | return impl->pltHookCommit();
286 | }
287 |
288 | } // namespace zygisk
289 |
290 | [[gnu::visibility("default")]] [[gnu::used]]
291 | extern "C" void zygisk_module_entry(zygisk::internal::api_table *, JNIEnv *);
292 |
293 | [[gnu::visibility("default")]] [[gnu::used]]
294 | extern "C" void zygisk_companion_entry(int);
295 |
--------------------------------------------------------------------------------