├── module ├── META-INF │ └── com │ │ └── google │ │ └── android │ │ ├── updater-script │ │ └── update-binary ├── module.prop ├── example.app_replace.list ├── example.pif.json ├── post-fs-data.sh ├── service.sh ├── common_func.sh ├── customize.sh ├── common_setup.sh └── migrate.sh ├── .idea ├── .gitignore ├── compiler.xml ├── inspectionProfiles │ ├── profiles_settings.xml │ └── Project_Default.xml ├── vcs.xml ├── deploymentTargetDropDown.xml ├── migrations.xml ├── misc.xml └── gradle.xml ├── app ├── src │ └── main │ │ ├── AndroidManifest.xml │ │ ├── cpp │ │ ├── CMakeLists.txt │ │ ├── main.cpp │ │ └── zygisk.hpp │ │ └── java │ │ └── es │ │ └── chiteroman │ │ └── playintegrityfix │ │ ├── Keybox.java │ │ ├── CustomProvider.java │ │ ├── CertUtils.java │ │ ├── XMLParser.java │ │ ├── CustomKeyStoreSpi.java │ │ ├── EntryPoint.java │ │ └── CustomKeyStoreKeyPairGeneratorSpi.java ├── proguard-rules.pro └── build.gradle.kts ├── .gitmodules ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── update.json ├── .gitignore ├── settings.gradle.kts ├── .github ├── FUNDING.yml └── workflows │ └── android.yml ├── CHANGELOG.md ├── gradle.properties ├── gradlew.bat ├── gradlew ├── README.md └── LICENSE /module/META-INF/com/google/android/updater-script: -------------------------------------------------------------------------------- 1 | #MAGISK 2 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "Dobby"] 2 | path = app/src/main/cpp/Dobby 3 | url = https://github.com/jmpews/Dobby 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hex3l/PlayIntegrityForkKsBypass/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /update.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "v8", 3 | "versionCode": 80000, 4 | "zipUrl": "https://github.com/osm0sis/PlayIntegrityFork/releases/download/v8/PlayIntegrityFork-v8.zip", 5 | "changelog": "https://raw.githubusercontent.com/osm0sis/PlayIntegrityFork/main/CHANGELOG.md" 6 | } 7 | -------------------------------------------------------------------------------- /.idea/deploymentTargetDropDown.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /.idea/migrations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .cxx 3 | .DS_Store 4 | .externalNativeBuild 5 | .gradle 6 | .idea/assetWizardSettings.xml 7 | .idea/caches 8 | .idea/libraries 9 | .idea/modules.xml 10 | .idea/navEditor.xml 11 | .idea/workspace.xml 12 | build/ 13 | local.properties 14 | module/classes.dex 15 | module/pif.json 16 | module/zygisk/ 17 | out/ 18 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | -keep class es.chiteroman.playintegrityfix.EntryPoint {public ;} 2 | -keep class es.chiteroman.playintegrityfix.CustomProvider 3 | -keep class es.chiteroman.playintegrityfix.CustomKeyStoreSpi 4 | -keep class es.chiteroman.playintegrityfix.CustomKeyStoreKeyPairGeneratorSpi$EC 5 | -keep class es.chiteroman.playintegrityfix.CustomKeyStoreKeyPairGeneratorSpi$RSA 6 | -------------------------------------------------------------------------------- /module/module.prop: -------------------------------------------------------------------------------- 1 | id=playintegrityfix 2 | name=Play Integrity Fork 3 | version=v8 4 | versionCode=80001 5 | author=hex3l & osm0sis & chiteroman @ xda-developers 6 | description=Fix CTS profile (SafetyNet) and DEVICE verdict (Play Integrity), provides a bypass for AndroidKeyStore using a keybox.xml 7 | updateJson=https://raw.githubusercontent.com/osm0sis/PlayIntegrityFork/main/update.json 8 | -------------------------------------------------------------------------------- /app/src/main/cpp/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.22.1) 2 | 3 | project(zygisk) 4 | 5 | find_package(cxx REQUIRED CONFIG) 6 | 7 | link_libraries(cxx::cxx) 8 | 9 | add_library(${CMAKE_PROJECT_NAME} SHARED ${CMAKE_SOURCE_DIR}/main.cpp) 10 | 11 | add_subdirectory(Dobby) 12 | 13 | SET_OPTION(Plugin.Android.BionicLinkerUtil ON) 14 | 15 | target_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE log dobby_static) 16 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | google() 4 | mavenCentral() 5 | gradlePluginPortal() 6 | } 7 | } 8 | dependencyResolutionManagement { 9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 10 | repositories { 11 | google() 12 | mavenCentral() 13 | } 14 | } 15 | 16 | rootProject.name = "PlayIntegrityFix" 17 | include(":app") 18 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/main/java/es/chiteroman/playintegrityfix/Keybox.java: -------------------------------------------------------------------------------- 1 | package es.chiteroman.playintegrityfix; 2 | 3 | import org.bouncycastle.asn1.x500.X500Name; 4 | 5 | import java.security.KeyPair; 6 | import java.security.PrivateKey; 7 | import java.security.cert.Certificate; 8 | import java.util.LinkedList; 9 | 10 | public record Keybox(KeyPair keypair, PrivateKey privateKey, LinkedList certificateChain, 11 | LinkedList certificateChainSubject) { 12 | 13 | } 14 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 10 | 11 | -------------------------------------------------------------------------------- /module/example.app_replace.list: -------------------------------------------------------------------------------- 1 | # Rename to custom.app_replace.list once customized 2 | # 3 | # Add conflicting custom ROM injection app folder/file paths to this list 4 | # and they will be replaced/hidden systemlessly to disable them 5 | 6 | # Xiaomi.eu 7 | /product/app/XiaomiEUInject 8 | /product/app/XiaomiEUInject-Stub 9 | 10 | # EliteRoms 11 | /system/app/EliteDevelopmentModule 12 | /system/app/XInjectModule 13 | 14 | # hentaiOS 15 | /system_ext/app/hentaiLewdbSVTDummy 16 | 17 | # Evolution X 18 | /system_ext/app/PifPrebuilt 19 | 20 | # PixelOS 21 | /system_ext/overlay/CertifiedPropsOverlay.apk 22 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /module/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 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: osm0sis # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: https://www.paypal.me/osm0sis # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /module/example.pif.json: -------------------------------------------------------------------------------- 1 | // Rename to custom.pif.json once completed 2 | // 3 | // See android.os.Build source for field value corresponding properties: 4 | // https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/Build.java 5 | 6 | { 7 | // Build Fields 8 | "MANUFACTURER": "", 9 | "MODEL": "", 10 | "FINGERPRINT": "", 11 | "BRAND": "", 12 | "PRODUCT": "", 13 | "DEVICE": "", 14 | "RELEASE": "", 15 | "ID": "", 16 | "INCREMENTAL": "", 17 | "TYPE": "", 18 | "TAGS": "", 19 | "SECURITY_PATCH": "", 20 | "DEVICE_INITIAL_SDK_INT": "", 21 | 22 | // System Properties 23 | "*.build.id": "", // for ro.build.id 24 | "*.security_patch": "", // for ro.build.version.security_patch 25 | "*api_level": "" // for ro.board.first_api_level, ro.product.first_api_level and ro.vendor.api_level 26 | } 27 | -------------------------------------------------------------------------------- /.github/workflows/android.yml: -------------------------------------------------------------------------------- 1 | name: Android CI 2 | 3 | on: 4 | push: 5 | branches: main 6 | paths-ignore: '**.md' 7 | pull_request: 8 | branches: main 9 | paths-ignore: '**.md' 10 | 11 | jobs: 12 | build: 13 | 14 | runs-on: macos-14 15 | 16 | steps: 17 | - name: Check out 18 | uses: actions/checkout@v4 19 | with: 20 | submodules: 'recursive' 21 | fetch-depth: 0 22 | 23 | - name: Set up JDK 24 | uses: actions/setup-java@v4 25 | with: 26 | distribution: 'temurin' 27 | java-version: 17 28 | 29 | - name: Grant execute permission for gradlew 30 | run: chmod +x gradlew 31 | 32 | - name: Build with Gradle 33 | run: ./gradlew assembleRelease 34 | 35 | - name: Upload CI module zip as artifact zip 36 | uses: actions/upload-artifact@v4 37 | with: 38 | name: PlayIntegrityFork-CI_#${{ github.run_number }} 39 | path: 'module/*' 40 | compression-level: 9 41 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## Custom Fork v8 2 | - Rename VERBOSE_LOGS to verboseLogs to better differentiate Advanced Settings from Build Fields or System Properties 3 | - Improve replace list to also allow file paths replacing/hiding systemlessly 4 | - Improve migration script and add optional verboseLogs entry to output 5 | - Improve replace list to automatically comment out any overlay APK config.xml entries systemlessly 6 | - Update default/example app replace list for more ROM spoof injection methods 7 | - Fix retaining disabled ROM apps through module updates in some scenarios 8 | 9 | ## Custom Fork v7 10 | - Fix non-/system ROM spoof injection app replacement 11 | - Add missing XiaomiEUInject-Stub to the default/example replace list 12 | - Improve code, scripts and logging 13 | - Fix ROM spoof injection app replacement when using KernelSU and APatch 14 | - Spoof init.svc.adbd to DroidGuard by default to further hide USB Debugging 15 | - Improve hiding from detection by user apps 16 | 17 | _[Previous changelogs](https://github.com/osm0sis/PlayIntegrityFork/releases)_ 18 | -------------------------------------------------------------------------------- /app/src/main/java/es/chiteroman/playintegrityfix/CustomProvider.java: -------------------------------------------------------------------------------- 1 | package es.chiteroman.playintegrityfix; 2 | 3 | import java.security.Provider; 4 | 5 | public final class CustomProvider extends Provider { 6 | 7 | CustomProvider(Provider provider) { 8 | super(provider.getName(), provider.getVersion(), provider.getInfo()); 9 | EntryPoint.LOG("Loading new provider"); 10 | putAll(provider); 11 | this.put("KeyStore.AndroidKeyStore", CustomKeyStoreSpi.class.getName()); 12 | this.put("KeyPairGenerator.EC", CustomKeyStoreKeyPairGeneratorSpi.EC.class.getName()); 13 | this.put("KeyPairGenerator.RSA", CustomKeyStoreKeyPairGeneratorSpi.RSA.class.getName()); 14 | this.put("KeyPairGenerator.OLDEC", provider.get("KeyPairGenerator.EC")); 15 | this.put("KeyPairGenerator.OLDRSA", provider.get("KeyPairGenerator.RSA")); 16 | } 17 | 18 | @Override 19 | public synchronized Service getService(String type, String algorithm) { 20 | if (EntryPoint.getVerboseLogs() > 2) EntryPoint.LOG(String.format("Service: Caller type '%s' with algorithm '%s'", type, algorithm)); 21 | if (type.equals("KeyStore")) EntryPoint.spoofDevice(); 22 | return super.getService(type, algorithm); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /module/post-fs-data.sh: -------------------------------------------------------------------------------- 1 | MODPATH="${0%/*}" 2 | . $MODPATH/common_func.sh 3 | 4 | if [ -d "$MODPATH/zygisk" ]; then 5 | # Remove Play Services from Magisk DenyList when set to Enforce in normal mode 6 | if magisk --denylist status; then 7 | magisk --denylist rm com.google.android.gms 8 | fi 9 | # Run common tasks for installation and boot-time 10 | . $MODPATH/common_setup.sh 11 | else 12 | # Add Play Services DroidGuard process to Magisk DenyList for better results in scripts-only mode 13 | magisk --denylist add com.google.android.gms com.google.android.gms.unstable 14 | fi 15 | 16 | # Conditional early sensitive properties 17 | 18 | # Samsung 19 | resetprop_if_diff ro.boot.warranty_bit 0 20 | resetprop_if_diff ro.vendor.boot.warranty_bit 0 21 | resetprop_if_diff ro.vendor.warranty_bit 0 22 | resetprop_if_diff ro.warranty_bit 0 23 | 24 | # Xiaomi 25 | resetprop_if_diff ro.secureboot.lockstate locked 26 | 27 | # Realme 28 | resetprop_if_diff ro.boot.realmebootstate green 29 | 30 | # OnePlus 31 | resetprop_if_diff ro.is_ever_orange 0 32 | 33 | # Microsoft 34 | resetprop_if_diff ro.build.tags release-keys 35 | 36 | # Other 37 | resetprop_if_diff ro.build.type user 38 | resetprop_if_diff ro.debuggable 0 39 | resetprop_if_diff ro.secure 1 40 | -------------------------------------------------------------------------------- /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 | # Enables namespacing of each library's R class so that its R class includes only the 19 | # resources declared in the library itself and none from the library's dependencies, 20 | # thereby reducing the size of the R class for that library 21 | android.nonTransitiveRClass=true 22 | -------------------------------------------------------------------------------- /module/service.sh: -------------------------------------------------------------------------------- 1 | MODPATH="${0%/*}" 2 | . $MODPATH/common_func.sh 3 | 4 | # Conditional sensitive properties 5 | 6 | # Magisk recovery mode 7 | resetprop_if_match ro.bootmode recovery unknown 8 | resetprop_if_match ro.boot.mode recovery unknown 9 | resetprop_if_match vendor.boot.mode recovery unknown 10 | 11 | # SELinux 12 | resetprop_if_diff ro.boot.selinux enforcing 13 | # use delete since it can be 0 or 1 for enforcing depending on OEM 14 | if [ -n "$(resetprop ro.build.selinux)" ]; then 15 | resetprop --delete ro.build.selinux 16 | fi 17 | # use toybox to protect *stat* access time reading 18 | if [ "$(toybox cat /sys/fs/selinux/enforce)" = "0" ]; then 19 | chmod 640 /sys/fs/selinux/enforce 20 | chmod 440 /sys/fs/selinux/policy 21 | fi 22 | 23 | # Conditional late sensitive properties 24 | 25 | # SafetyNet/Play Integrity 26 | { 27 | # must be set after boot_completed for various OEMs 28 | until [ "$(getprop sys.boot_completed)" = "1" ]; do 29 | sleep 1 30 | done 31 | 32 | # avoid breaking Realme fingerprint scanners 33 | resetprop_if_diff ro.boot.flash.locked 1 34 | resetprop_if_diff ro.boot.realme.lockstate 1 35 | 36 | # avoid breaking Oppo fingerprint scanners 37 | resetprop_if_diff ro.boot.vbmeta.device_state locked 38 | 39 | # avoid breaking OnePlus display modes/fingerprint scanners 40 | resetprop_if_diff vendor.boot.verifiedbootstate green 41 | 42 | # avoid breaking OnePlus/Oppo fingerprint scanners on OOS/ColorOS 12+ 43 | resetprop_if_diff ro.boot.verifiedbootstate green 44 | resetprop_if_diff ro.boot.veritymode enforcing 45 | resetprop_if_diff vendor.boot.vbmeta.device_state locked 46 | }& 47 | -------------------------------------------------------------------------------- /module/common_func.sh: -------------------------------------------------------------------------------- 1 | # resetprop_hexpatch [-f|--force] 2 | resetprop_hexpatch() { 3 | case "$1" in 4 | -f|--force) local FORCE=1; shift;; 5 | esac 6 | 7 | local NAME="$1" 8 | local NEWVALUE="$2" 9 | local CURVALUE="$(resetprop "$NAME")" 10 | 11 | [ ! "$NEWVALUE" -o ! "$CURVALUE" ] && return 1 12 | [ "$NEWVALUE" = "$CURVALUE" -a ! "$FORCE" ] && return 2 13 | 14 | local NEWLEN=${#NEWVALUE} 15 | if [ -f /dev/__properties__ ]; then 16 | local PROPFILE=/dev/__properties__ 17 | else 18 | local PROPFILE="/dev/__properties__/$(resetprop -Z "$NAME")" 19 | fi 20 | [ ! -f "$PROPFILE" ] && return 3 21 | local NAMEOFFSET=$(echo $(strings -t d "$PROPFILE" | grep "$NAME") | cut -d ' ' -f 1) 22 | 23 | # 24 | local NEWHEX="$(printf '%02x' "$NEWLEN")$(printf "$NEWVALUE" | od -A n -t x1 -v | tr -d ' \n')$(printf "%$((92-NEWLEN))s" | sed 's/ /00/g')" 25 | 26 | printf "Patch '$NAME' to '$NEWVALUE' in '$PROPFILE' @ 0x%08x -> \n[0000??$NEWHEX]\n" $((NAMEOFFSET-96)) 27 | 28 | echo -ne "\x00\x00" \ 29 | | dd obs=1 count=2 seek=$((NAMEOFFSET-96)) conv=notrunc of="$PROPFILE" 30 | echo -ne "$(printf "$NEWHEX" | sed -e 's/.\{2\}/&\\x/g' -e 's/^/\\x/' -e 's/\\x$//')" \ 31 | | dd obs=1 count=93 seek=$((NAMEOFFSET-93)) conv=notrunc of="$PROPFILE" 32 | } 33 | 34 | # resetprop_if_diff 35 | resetprop_if_diff() { 36 | local NAME="$1" 37 | local EXPECTED="$2" 38 | local CURRENT="$(resetprop "$NAME")" 39 | 40 | [ -z "$CURRENT" ] || [ "$CURRENT" = "$EXPECTED" ] || resetprop_hexpatch "$NAME" "$EXPECTED" 41 | } 42 | 43 | # resetprop_if_match 44 | resetprop_if_match() { 45 | local NAME="$1" 46 | local CONTAINS="$2" 47 | local VALUE="$3" 48 | 49 | [[ "$(resetprop "$NAME")" = *"$CONTAINS"* ]] && resetprop_hexpatch "$NAME" "$VALUE" 50 | } 51 | 52 | # stub for boot-time 53 | ui_print() { return; } 54 | -------------------------------------------------------------------------------- /module/customize.sh: -------------------------------------------------------------------------------- 1 | # Allow a scripts-only mode on older Android without Zygisk 2 | if [ "$API" -lt 26 -o -f /data/adb/modules/playintegrityfix/scripts-only-mode ]; then 3 | ui_print "! Installing global scripts only for Android < 8.0; Zygisk attestation fallback and device spoofing disabled" 4 | touch $MODPATH/scripts-only-mode 5 | rm -rf $MODPATH/classes.dex $MODPATH/common_setup.sh $MODPATH/custom.pif.json \ 6 | $MODPATH/example.app_replace.list $MODPATH/example.pif.json $MODPATH/migrate.sh $MODPATH/zygisk \ 7 | /data/adb/modules/playintegrityfix/custom.app_replace.list \ 8 | /data/adb/modules/playintegrityfix/custom.pif.json /data/adb/modules/playintegrityfix/system 9 | fi 10 | 11 | # Copy any disabled app files to updated module 12 | if [ -d /data/adb/modules/playintegrityfix/system ]; then 13 | ui_print "- Restoring disabled ROM apps configuration" 14 | cp -arf /data/adb/modules/playintegrityfix/system $MODPATH 15 | fi 16 | 17 | # Copy any supported custom files to updated module 18 | for FILE in custom.app_replace.list custom.pif.json keybox.xml; do 19 | if [ -f "/data/adb/modules/playintegrityfix/$FILE" ]; then 20 | ui_print "- Restoring $FILE" 21 | cp -af /data/adb/modules/playintegrityfix/$FILE $MODPATH/$FILE 22 | fi 23 | done 24 | 25 | # Warn if potentially conflicting modules are installed 26 | if [ -d /data/adb/modules/MagiskHidePropsConf ]; then 27 | ui_print "! MagiskHidePropsConfig (MHPC) module may cause issues with PIF" 28 | fi 29 | 30 | # Run common tasks for installation and boot-time 31 | [ -d "$MODPATH/zygisk" ] && . $MODPATH/common_setup.sh 32 | 33 | # Migrate custom.pif.json to latest defaults if needed 34 | if [ -f "$MODPATH/custom.pif.json" ] && ! grep -q "api_level" $MODPATH/custom.pif.json; then 35 | ui_print "- Running migration script on custom.pif.json:" 36 | ui_print " " 37 | chmod 755 $MODPATH/migrate.sh 38 | sh $MODPATH/migrate.sh install $MODPATH/custom.pif.json 39 | ui_print " " 40 | fi 41 | 42 | # Clean up any leftover files from previous deprecated methods 43 | rm -f /data/data/com.google.android.gms/cache/pif.prop /data/data/com.google.android.gms/pif.prop \ 44 | /data/data/com.google.android.gms/cache/pif.json /data/data/com.google.android.gms/pif.json 45 | -------------------------------------------------------------------------------- /app/src/main/java/es/chiteroman/playintegrityfix/CertUtils.java: -------------------------------------------------------------------------------- 1 | package es.chiteroman.playintegrityfix; 2 | 3 | import org.bouncycastle.asn1.x500.X500Name; 4 | import org.bouncycastle.cert.X509CertificateHolder; 5 | import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; 6 | import org.bouncycastle.openssl.PEMKeyPair; 7 | import org.bouncycastle.openssl.PEMParser; 8 | import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; 9 | import org.bouncycastle.util.io.pem.PemObject; 10 | import org.bouncycastle.util.io.pem.PemReader; 11 | 12 | import java.io.IOException; 13 | import java.io.StringReader; 14 | import java.security.KeyPair; 15 | import java.security.PrivateKey; 16 | import java.security.cert.Certificate; 17 | 18 | public class CertUtils { 19 | 20 | public static Certificate parseCert(String cert) throws Throwable { 21 | PemObject pemObject; 22 | try (PemReader reader = new PemReader(new StringReader(cert))) { 23 | pemObject = reader.readPemObject(); 24 | } 25 | 26 | X509CertificateHolder holder = new X509CertificateHolder(pemObject.getContent()); 27 | 28 | return (new JcaX509CertificateConverter().getCertificate(holder)); 29 | } 30 | 31 | public static X500Name parseCertSubject(String cert) throws Throwable { 32 | PemObject pemObject; 33 | try (PemReader reader = new PemReader(new StringReader(cert))) { 34 | pemObject = reader.readPemObject(); 35 | } 36 | 37 | X509CertificateHolder holder = new X509CertificateHolder(pemObject.getContent()); 38 | 39 | return holder.getSubject(); 40 | } 41 | 42 | public static KeyPair parseKeyPair(String key) throws Throwable { 43 | Object object; 44 | try (PEMParser parser = new PEMParser(new StringReader(key))) { 45 | object = parser.readObject(); 46 | } 47 | 48 | PEMKeyPair pemKeyPair = (PEMKeyPair) object; 49 | 50 | return new JcaPEMKeyConverter().getKeyPair(pemKeyPair); 51 | } 52 | 53 | public static PrivateKey parsePrivateKey(String keyPair) throws RuntimeException { 54 | try (PEMParser parser = new PEMParser(new StringReader(keyPair))) { 55 | PEMKeyPair pemKeyPair = (PEMKeyPair) parser.readObject(); 56 | return new JcaPEMKeyConverter().getPrivateKey(pemKeyPair.getPrivateKeyInfo()); 57 | } catch (IOException e) { 58 | throw new RuntimeException(e); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /module/common_setup.sh: -------------------------------------------------------------------------------- 1 | # Remove any definitely conflicting modules that are installed 2 | if [ -d /data/adb/modules/safetynet-fix ]; then 3 | touch /data/adb/modules/safetynet-fix/remove 4 | ui_print "! Universal SafetyNet Fix (USNF) module will be removed on next reboot" 5 | fi 6 | 7 | # Replace/hide conflicting custom ROM injection app folders/files to disable them 8 | LIST=$MODPATH/example.app_replace.list 9 | [ -f "$MODPATH/custom.app_replace.list" ] && LIST=$MODPATH/custom.app_replace.list 10 | for APP in $(grep -v '^#' $LIST); do 11 | if [ -e "$APP" ]; then 12 | case $APP in 13 | /system/*) ;; 14 | *) PREFIX=/system;; 15 | esac 16 | HIDEPATH=$MODPATH$PREFIX$APP 17 | if [ -d "$APP" ]; then 18 | mkdir -p $HIDEPATH 19 | if [ "$KSU" = "true" -o "$APATCH" = "true" ]; then 20 | setfattr -n trusted.overlay.opaque -v y $HIDEPATH 21 | else 22 | touch $HIDEPATH/.replace 23 | fi 24 | else 25 | mkdir -p $(dirname $HIDEPATH) 26 | if [ "$KSU" = "true" -o "$APATCH" = "true" ]; then 27 | mknod $HIDEPATH c 0 0 28 | else 29 | touch $HIDEPATH 30 | fi 31 | fi 32 | case $APP in 33 | */overlay/*) 34 | CFG=$(echo $APP | grep -oE '.*/overlay')/config/config.xml 35 | if [ -f "$CFG" ]; then 36 | if [ -d "$APP" ]; then 37 | APK=$(readlink -f $APP/*.apk); 38 | elif [[ "$APP" = *".apk" ]]; then 39 | APK=$(readlink -f $APP); 40 | fi 41 | if [ -s "$APK" ]; then 42 | PKGNAME=$(unzip -p $APK AndroidManifest.xml | tr -d '\0' | grep -oE '[[:alnum:].-_]+\*http' | cut -d\* -f1) 43 | if [ "$PKGNAME" ] && grep -q "overlay package=\"$PKGNAME" $CFG; then 44 | HIDECFG=$MODPATH$PREFIX$CFG 45 | if [ ! -f "$HIDECFG" ]; then 46 | mkdir -p $(dirname $HIDECFG) 47 | cp -af $CFG $HIDECFG 48 | fi 49 | sed -i 's;;;' $HIDECFG 50 | fi 51 | fi 52 | fi 53 | ;; 54 | esac 55 | if [[ -d "$APP" || "$APP" = *".apk" ]]; then 56 | ui_print "! $(basename $APP .apk) ROM app disabled, please uninstall any user app versions/updates after next reboot" 57 | [ "$HIDECFG" ] && ui_print "! + $PKGNAME entry commented out in copied overlay config" 58 | fi 59 | fi 60 | done 61 | -------------------------------------------------------------------------------- /app/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("com.android.application") 3 | } 4 | 5 | android { 6 | namespace = "es.chiteroman.playintegrityfix" 7 | compileSdk = 34 8 | ndkVersion = "26.2.11394342" 9 | buildToolsVersion = "34.0.0" 10 | 11 | buildFeatures { 12 | prefab = true 13 | } 14 | 15 | packaging { 16 | jniLibs { 17 | excludes += "**/liblog.so" 18 | excludes += "**/libdobby.so" 19 | } 20 | } 21 | 22 | defaultConfig { 23 | applicationId = "es.chiteroman.playintegrityfix" 24 | minSdk = 26 25 | targetSdk = 34 26 | versionCode = 1 27 | versionName = "1.0" 28 | 29 | externalNativeBuild { 30 | cmake { 31 | arguments += "-DANDROID_STL=none" 32 | arguments += "-DCMAKE_BUILD_TYPE=Release" 33 | 34 | cppFlags += "-std=c++20" 35 | cppFlags += "-fno-exceptions" 36 | cppFlags += "-fno-rtti" 37 | cppFlags += "-fvisibility=hidden" 38 | cppFlags += "-fvisibility-inlines-hidden" 39 | } 40 | } 41 | } 42 | 43 | buildTypes { 44 | release { 45 | isMinifyEnabled = true 46 | isShrinkResources = true 47 | proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") 48 | } 49 | } 50 | 51 | compileOptions { 52 | sourceCompatibility = JavaVersion.VERSION_17 53 | targetCompatibility = JavaVersion.VERSION_17 54 | } 55 | 56 | externalNativeBuild { 57 | cmake { 58 | path = file("src/main/cpp/CMakeLists.txt") 59 | version = "3.22.1" 60 | } 61 | } 62 | } 63 | 64 | dependencies { 65 | implementation("dev.rikka.ndk.thirdparty:cxx:1.2.0") 66 | implementation("org.bouncycastle:bcpkix-jdk18on:1.77") 67 | } 68 | 69 | tasks.register("copyFiles") { 70 | doLast { 71 | val moduleFolder = project.rootDir.resolve("module") 72 | val dexFile = project.layout.buildDirectory.get().asFile.resolve("intermediates/dex/release/minifyReleaseWithR8/classes.dex") 73 | val soDir = project.layout.buildDirectory.get().asFile.resolve("intermediates/stripped_native_libs/release/stripReleaseDebugSymbols/out/lib") 74 | 75 | dexFile.copyTo(moduleFolder.resolve("classes.dex"), overwrite = true) 76 | 77 | soDir.walk().filter { it.isFile && it.extension == "so" }.forEach { soFile -> 78 | val abiFolder = soFile.parentFile.name 79 | val destination = moduleFolder.resolve("zygisk/$abiFolder.so") 80 | soFile.copyTo(destination, overwrite = true) 81 | } 82 | } 83 | } 84 | 85 | tasks.register("zip") { 86 | dependsOn("copyFiles") 87 | 88 | archiveFileName.set("PlayIntegrityFork.zip") 89 | destinationDirectory.set(project.rootDir.resolve("out")) 90 | 91 | from(project.rootDir.resolve("module")) 92 | } 93 | 94 | afterEvaluate { 95 | tasks["assembleRelease"].finalizedBy("copyFiles", "zip") 96 | } 97 | -------------------------------------------------------------------------------- /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. 1>&2 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 48 | echo. 1>&2 49 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 50 | echo location of your Java installation. 1>&2 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. 1>&2 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 62 | echo. 1>&2 63 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 64 | echo location of your Java installation. 1>&2 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 | -------------------------------------------------------------------------------- /module/migrate.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | case "$1" in 4 | -h|--help|help) echo "sh migrate.sh [-f] [-a] [in-file] [out-file]"; exit 0;; 5 | esac; 6 | 7 | N=" 8 | "; 9 | 10 | case "$1" in 11 | -i|--install|install) INSTALL=1; shift;; 12 | *) echo "custom.pif.json migration script \ 13 | $N by osm0sis @ xda-developers $N";; 14 | esac; 15 | 16 | item() { echo "- $@"; } 17 | die() { [ "$INSTALL" ] || echo "$N$N! $@"; exit 1; } 18 | grep_get_json() { cat "$FILE" | tr -d '\r\n' | grep -m1 -owE "$1"'"[^,}]+"' | cut -d\" -f3; } 19 | grep_check_json() { grep -q "$1" "$FILE" && [ "$(grep_get_json $1)" ]; } 20 | 21 | case "$1" in 22 | -f|--force|force) FORCE=1; shift;; 23 | esac; 24 | case "$1" in 25 | -a|--advanced|advanced) ADVANCED=1; shift;; 26 | esac; 27 | 28 | if [ -f "$1" ]; then 29 | FILE="$1"; 30 | DIR="$1"; 31 | else 32 | case "$0" in 33 | *.sh) DIR="$0";; 34 | *) DIR="$(lsof -p $$ 2>/dev/null | grep -o '/.*migrate.sh$')";; 35 | esac; 36 | fi; 37 | DIR=$(dirname "$(readlink -f "$DIR")"); 38 | [ -z "$FILE" ] && FILE="$DIR/custom.pif.json"; 39 | 40 | OUT="$2"; 41 | [ -z "$OUT" ] && OUT="$DIR/custom.pif.json"; 42 | 43 | [ -f "$FILE" ] || die "No json file found"; 44 | 45 | grep_check_json api_level && [ ! "$FORCE" ] && die "No migration required"; 46 | 47 | [ "$INSTALL" ] || item "Parsing fields ..."; 48 | 49 | FPFIELDS="BRAND PRODUCT DEVICE RELEASE ID INCREMENTAL TYPE TAGS"; 50 | ALLFIELDS="MANUFACTURER MODEL FINGERPRINT $FPFIELDS SECURITY_PATCH DEVICE_INITIAL_SDK_INT"; 51 | 52 | for FIELD in $ALLFIELDS; do 53 | eval $FIELD=\"$(grep_get_json $FIELD)\"; 54 | done; 55 | 56 | if [ -n "$ID" ] && ! grep_check_json build.id; then 57 | item 'Simple entry ID found, changing to ID field and "*.build.id" property ...'; 58 | fi; 59 | 60 | if [ -z "$ID" ] && grep_check_json BUILD_ID; then 61 | item 'Deprecated entry BUILD_ID found, changing to ID field and "*.build.id" property ...'; 62 | ID="$(grep_get_json BUILD_ID)"; 63 | fi; 64 | 65 | if [ -n "$SECURITY_PATCH" ] && ! grep_check_json security_patch; then 66 | item 'Simple entry SECURITY_PATCH found, changing to SECURITY_PATCH field and "*.security_patch" property ...'; 67 | fi; 68 | 69 | if grep_check_json VNDK_VERSION; then 70 | item 'Deprecated entry VNDK_VERSION found, changing to "*.vndk.version" property ...'; 71 | VNDK_VERSION="$(grep_get_json VNDK_VERSION)"; 72 | fi; 73 | 74 | if [ -n "$DEVICE_INITIAL_SDK_INT" ] && ! grep_check_json api_level; then 75 | item 'Simple entry DEVICE_INITIAL_SDK_INT found, changing to DEVICE_INITIAL_SDK_INT field and "*api_level" property ...'; 76 | fi; 77 | 78 | if [ -z "$DEVICE_INITIAL_SDK_INT" ] && grep_check_json FIRST_API_LEVEL; then 79 | item 'Deprecated entry FIRST_API_LEVEL found, changing to DEVICE_INITIAL_SDK_INT field and "*api_level" property ...'; 80 | DEVICE_INITIAL_SDK_INT="$(grep_get_json FIRST_API_LEVEL)"; 81 | fi; 82 | 83 | if [ -z "$RELEASE" -o -z "$INCREMENTAL" -o -z "$TYPE" -o -z "$TAGS" ]; then 84 | item "Missing default fields found, deriving from FINGERPRINT ..."; 85 | IFS='/:' read F1 F2 F3 F4 F5 F6 F7 F8 < "$OUT"; 126 | 127 | [ "$INSTALL" ] || cat "$OUT"; 128 | -------------------------------------------------------------------------------- /app/src/main/java/es/chiteroman/playintegrityfix/XMLParser.java: -------------------------------------------------------------------------------- 1 | /** 2 | * PlayIntegrityForkKsBypass bypass AndroidKeyStore with specified keybox 3 | * Copyright (C) 2024 hex3l 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | package es.chiteroman.playintegrityfix; 20 | 21 | import org.xmlpull.v1.XmlPullParser; 22 | import org.xmlpull.v1.XmlPullParserException; 23 | import org.xmlpull.v1.XmlPullParserFactory; 24 | 25 | import java.io.IOException; 26 | import java.io.StringReader; 27 | import java.util.HashMap; 28 | import java.util.Map; 29 | 30 | public class XMLParser { 31 | 32 | private final String xml; 33 | 34 | public XMLParser(String xml) { 35 | this.xml = xml; 36 | } 37 | 38 | public Map obtainPath(String path) throws Exception { 39 | XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance(); 40 | XmlPullParser parser = xmlFactoryObject.newPullParser(); 41 | parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); 42 | parser.setInput(new StringReader(xml)); 43 | 44 | String[] tags = path.split("\\."); 45 | 46 | return readData(parser, tags, 0, new HashMap<>()); 47 | } 48 | 49 | private Map readData(XmlPullParser parser, String[] tags, int index, Map tagCounts) throws IOException, XmlPullParserException { 50 | while (parser.next() != XmlPullParser.END_DOCUMENT) { 51 | if (parser.getEventType() != XmlPullParser.START_TAG) { 52 | continue; 53 | } 54 | 55 | String name = parser.getName(); 56 | 57 | if (name.equals(tags[index].split("\\[")[0])) { 58 | 59 | String[] tagParts = tags[index].split("\\["); 60 | if (tagParts.length > 1) { 61 | if (tagCounts.getOrDefault(name, 0) < Integer.parseInt(tagParts[1].replace("]", ""))) { 62 | tagCounts.put(name, tagCounts.getOrDefault(name, 0) + 1); 63 | return readData(parser, tags, index, tagCounts); 64 | } else { 65 | if (index == tags.length - 1) { 66 | return readAttributes(parser); 67 | } else { 68 | return readData(parser, tags, index + 1, tagCounts); 69 | } 70 | } 71 | } else { 72 | if (index == tags.length - 1) { 73 | return readAttributes(parser); 74 | } else { 75 | return readData(parser, tags, index + 1, tagCounts); 76 | } 77 | } 78 | } else { 79 | skip(parser); 80 | } 81 | } 82 | 83 | throw new XmlPullParserException("Path not found"); 84 | } 85 | 86 | private Map readAttributes(XmlPullParser parser) throws IOException, XmlPullParserException { 87 | Map attributes = new HashMap<>(); 88 | for (int i = 0; i < parser.getAttributeCount(); i++) { 89 | attributes.put(parser.getAttributeName(i), parser.getAttributeValue(i)); 90 | } 91 | if (parser.next() == XmlPullParser.TEXT) { 92 | attributes.put("text", parser.getText()); 93 | } 94 | return attributes; 95 | } 96 | 97 | private void skip(XmlPullParser parser) throws XmlPullParserException, IOException { 98 | if (parser.getEventType() != XmlPullParser.START_TAG) { 99 | throw new IllegalStateException(); 100 | } 101 | int depth = 1; 102 | while (depth != 0) { 103 | switch (parser.next()) { 104 | case XmlPullParser.END_TAG: 105 | depth--; 106 | break; 107 | case XmlPullParser.START_TAG: 108 | depth++; 109 | break; 110 | } 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /app/src/main/java/es/chiteroman/playintegrityfix/CustomKeyStoreSpi.java: -------------------------------------------------------------------------------- 1 | package es.chiteroman.playintegrityfix; 2 | 3 | import android.util.Log; 4 | 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.io.OutputStream; 8 | import java.security.Key; 9 | import java.security.KeyStoreException; 10 | import java.security.KeyStoreSpi; 11 | import java.security.NoSuchAlgorithmException; 12 | import java.security.UnrecoverableKeyException; 13 | import java.security.cert.Certificate; 14 | import java.security.cert.CertificateException; 15 | import java.security.cert.X509Certificate; 16 | import java.util.Date; 17 | import java.util.Enumeration; 18 | import java.util.LinkedList; 19 | import java.util.Locale; 20 | import java.util.Objects; 21 | 22 | public final class CustomKeyStoreSpi extends KeyStoreSpi { 23 | 24 | public static volatile KeyStoreSpi keyStoreSpi; 25 | 26 | @Override 27 | public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException { 28 | return keyStoreSpi.engineGetKey(alias, password); 29 | } 30 | 31 | @Override 32 | public Certificate[] engineGetCertificateChain(String alias) { 33 | for (StackTraceElement e : Thread.currentThread().getStackTrace()) { 34 | // TODO hex3l: switch to droidguard, currently implemented only for key attest test app 35 | if (e.getClassName().toLowerCase(Locale.ROOT).contains("vvb2060")) { 36 | EntryPoint.LOG("GetChain Certificate alias requested: " + alias); 37 | Certificate leaf = EntryPoint.retrieve(alias); 38 | if (leaf != null) { 39 | EntryPoint.LOG("GetChain alias certificates: " + leaf.getType() + " " + leaf.hashCode() + " "); 40 | LinkedList certificateList = new LinkedList<>(); 41 | 42 | try { 43 | if (((X509Certificate) leaf).getSigAlgName().contains("ECDSA")) { 44 | certificateList.addAll((Objects.requireNonNull(EntryPoint.box("ecdsa"))).certificateChain()); 45 | } else { 46 | certificateList.addAll((Objects.requireNonNull(EntryPoint.box("rsa"))).certificateChain()); 47 | } 48 | } catch (Throwable t) { 49 | Log.e("GetChain unable to ", t.toString()); 50 | } 51 | certificateList.addFirst(leaf); 52 | 53 | return certificateList.toArray(new Certificate[0]); 54 | } 55 | throw new UnsupportedOperationException(); 56 | } 57 | // TODO hex3l: remove fallback to device when ready to bypass keystore for droidguard 58 | if(e.getClassName().toLowerCase(Locale.ROOT).contains("droidguard")) { 59 | throw new UnsupportedOperationException(); 60 | } 61 | } 62 | return keyStoreSpi.engineGetCertificateChain(alias); 63 | } 64 | 65 | @Override 66 | public Certificate engineGetCertificate(String alias) { 67 | return keyStoreSpi.engineGetCertificate(alias); 68 | } 69 | 70 | @Override 71 | public Date engineGetCreationDate(String alias) { 72 | return keyStoreSpi.engineGetCreationDate(alias); 73 | } 74 | 75 | @Override 76 | public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) throws KeyStoreException { 77 | keyStoreSpi.engineSetKeyEntry(alias, key, password, chain); 78 | } 79 | 80 | @Override 81 | public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) throws KeyStoreException { 82 | keyStoreSpi.engineSetKeyEntry(alias, key, chain); 83 | } 84 | 85 | @Override 86 | public void engineSetCertificateEntry(String alias, Certificate cert) throws KeyStoreException { 87 | keyStoreSpi.engineSetCertificateEntry(alias, cert); 88 | } 89 | 90 | @Override 91 | public void engineDeleteEntry(String alias) throws KeyStoreException { 92 | keyStoreSpi.engineDeleteEntry(alias); 93 | } 94 | 95 | @Override 96 | public Enumeration engineAliases() { 97 | return keyStoreSpi.engineAliases(); 98 | } 99 | 100 | @Override 101 | public boolean engineContainsAlias(String alias) { 102 | return keyStoreSpi.engineContainsAlias(alias); 103 | } 104 | 105 | @Override 106 | public int engineSize() { 107 | return keyStoreSpi.engineSize(); 108 | } 109 | 110 | @Override 111 | public boolean engineIsKeyEntry(String alias) { 112 | return keyStoreSpi.engineIsKeyEntry(alias); 113 | } 114 | 115 | @Override 116 | public boolean engineIsCertificateEntry(String alias) { 117 | return keyStoreSpi.engineIsCertificateEntry(alias); 118 | } 119 | 120 | @Override 121 | public String engineGetCertificateAlias(Certificate cert) { 122 | return keyStoreSpi.engineGetCertificateAlias(cert); 123 | } 124 | 125 | @Override 126 | public void engineStore(OutputStream stream, char[] password) throws CertificateException, IOException, NoSuchAlgorithmException { 127 | keyStoreSpi.engineStore(stream, password); 128 | } 129 | 130 | @Override 131 | public void engineLoad(InputStream stream, char[] password) throws CertificateException, IOException, NoSuchAlgorithmException { 132 | keyStoreSpi.engineLoad(stream, password); 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /app/src/main/java/es/chiteroman/playintegrityfix/EntryPoint.java: -------------------------------------------------------------------------------- 1 | package es.chiteroman.playintegrityfix; 2 | 3 | import android.os.Build; 4 | import android.util.JsonReader; 5 | import android.util.Log; 6 | 7 | import org.bouncycastle.asn1.x500.X500Name; 8 | 9 | import java.io.IOException; 10 | import java.io.StringReader; 11 | import java.lang.reflect.Field; 12 | import java.security.KeyStore; 13 | import java.security.KeyStoreException; 14 | import java.security.KeyStoreSpi; 15 | import java.security.Provider; 16 | import java.security.Security; 17 | import java.security.cert.Certificate; 18 | import java.util.HashMap; 19 | import java.util.LinkedList; 20 | import java.util.Map; 21 | import java.util.Objects; 22 | 23 | public final class EntryPoint { 24 | private static Integer verboseLogs = 0; 25 | 26 | private static final Map map = new HashMap<>(); 27 | 28 | private static final Map certs = new HashMap<>(); 29 | 30 | private static final Map store = new HashMap<>(); 31 | 32 | public static Integer getVerboseLogs() { 33 | return verboseLogs; 34 | } 35 | 36 | public static void init(int level) { 37 | verboseLogs = level; 38 | if (verboseLogs > 99) logFields(); 39 | spoofProvider(); 40 | spoofDevice(); 41 | } 42 | 43 | public static void receiveJson(String data) { 44 | try (JsonReader reader = new JsonReader(new StringReader(data))) { 45 | reader.beginObject(); 46 | while (reader.hasNext()) { 47 | map.put(reader.nextName(), reader.nextString()); 48 | } 49 | reader.endObject(); 50 | } catch (IOException|IllegalStateException e) { 51 | LOG("Couldn't read JSON from Zygisk: " + e); 52 | map.clear(); 53 | return; 54 | } 55 | } 56 | 57 | public static void receiveXml(String data) { 58 | XMLParser xmlParser = new XMLParser(data); 59 | 60 | try { 61 | int numberOfKeyboxes = Integer.parseInt(Objects.requireNonNull(xmlParser.obtainPath("AndroidAttestation.NumberOfKeyboxes").get("text"))); 62 | for (int i = 0; i < numberOfKeyboxes; i++) { 63 | String keyboxAlgorithm = xmlParser.obtainPath("AndroidAttestation.Keybox.Key[" + i + "]").get("algorithm"); 64 | String privateKey = xmlParser.obtainPath("AndroidAttestation.Keybox.Key[" + i + "].PrivateKey").get("text"); 65 | 66 | int numberOfCertificates = Integer.parseInt(Objects.requireNonNull(xmlParser.obtainPath("AndroidAttestation.Keybox.Key[" + i + "].CertificateChain.NumberOfCertificates").get("text"))); 67 | 68 | LinkedList certificateChain = new LinkedList<>(); 69 | LinkedList certificateChainHolders = new LinkedList<>(); 70 | for (int j = 0; j < numberOfCertificates; j++) { 71 | Map certData= xmlParser.obtainPath("AndroidAttestation.Keybox.Key[" + i + "].CertificateChain.Certificate[" + j + "]"); 72 | certificateChain.add(CertUtils.parseCert(certData.get("text"))); 73 | certificateChainHolders.add(CertUtils.parseCertSubject(certData.get("text"))); 74 | } 75 | certs.put(keyboxAlgorithm, new Keybox(CertUtils.parseKeyPair(privateKey), CertUtils.parsePrivateKey(privateKey), certificateChain, certificateChainHolders)); 76 | } 77 | } catch (Throwable e) { 78 | LOG("Couldn't read box XML: " + e); 79 | map.clear(); 80 | return; 81 | } 82 | } 83 | 84 | private static void spoofProvider() { 85 | final String KEYSTORE = "AndroidKeyStore"; 86 | 87 | try { 88 | Provider provider = Security.getProvider(KEYSTORE); 89 | KeyStore keyStore = KeyStore.getInstance(KEYSTORE); 90 | 91 | Field f = keyStore.getClass().getDeclaredField("keyStoreSpi"); 92 | f.setAccessible(true); 93 | CustomKeyStoreSpi.keyStoreSpi = (KeyStoreSpi) f.get(keyStore); 94 | f.setAccessible(false); 95 | 96 | CustomProvider customProvider = new CustomProvider(provider); 97 | Security.removeProvider(KEYSTORE); 98 | Security.insertProviderAt(customProvider, 1); 99 | LOG("Spoof KeyStoreSpi and Provider done!"); 100 | 101 | } catch (KeyStoreException e) { 102 | LOG("Couldn't find KeyStore: " + e); 103 | } catch (NoSuchFieldException e) { 104 | LOG("Couldn't find field: " + e); 105 | } catch (IllegalAccessException e) { 106 | LOG("Couldn't change access of field: " + e); 107 | } 108 | } 109 | 110 | static void spoofDevice() { 111 | for (String key : map.keySet()) { 112 | setField(key, map.get(key)); 113 | } 114 | } 115 | 116 | private static boolean classContainsField(Class className, String fieldName) { 117 | for (Field field : className.getDeclaredFields()) { 118 | if (field.getName().equals(fieldName)) return true; 119 | } 120 | return false; 121 | } 122 | 123 | private static void setField(String name, String value) { 124 | if (value.isEmpty()) { 125 | LOG(String.format("%s is empty, skipping", name)); 126 | return; 127 | } 128 | 129 | Field field = null; 130 | String oldValue = null; 131 | Object newValue = null; 132 | 133 | try { 134 | if (classContainsField(Build.class, name)) { 135 | field = Build.class.getDeclaredField(name); 136 | } else if (classContainsField(Build.VERSION.class, name)) { 137 | field = Build.VERSION.class.getDeclaredField(name); 138 | } else { 139 | if (verboseLogs > 1) LOG(String.format("Couldn't determine '%s' class name", name)); 140 | return; 141 | } 142 | } catch (NoSuchFieldException e) { 143 | LOG(String.format("Couldn't find '%s' field name: " + e, name)); 144 | return; 145 | } 146 | field.setAccessible(true); 147 | try { 148 | oldValue = String.valueOf(field.get(null)); 149 | } catch (IllegalAccessException e) { 150 | LOG(String.format("Couldn't access '%s' field value: " + e, name)); 151 | return; 152 | } 153 | if (value.equals(oldValue)) { 154 | if (verboseLogs > 2) LOG(String.format("[%s]: %s (unchanged)", name, value)); 155 | return; 156 | } 157 | Class fieldType = field.getType(); 158 | if (fieldType == String.class) { 159 | newValue = value; 160 | } else if (fieldType == int.class) { 161 | newValue = Integer.parseInt(value); 162 | } else if (fieldType == long.class) { 163 | newValue = Long.parseLong(value); 164 | } else if (fieldType == boolean.class) { 165 | newValue = Boolean.parseBoolean(value); 166 | } else { 167 | LOG(String.format("Couldn't convert '%s' to '%s' type", value, fieldType)); 168 | return; 169 | } 170 | try { 171 | field.set(null, newValue); 172 | } catch (IllegalAccessException e) { 173 | LOG(String.format("Couldn't modify '%s' field value: " + e, name)); 174 | return; 175 | } 176 | field.setAccessible(false); 177 | LOG(String.format("[%s]: %s -> %s", name, oldValue, value)); 178 | } 179 | 180 | private static String logParseField(Field field) { 181 | Object value = null; 182 | String type = field.getType().getName(); 183 | String name = field.getName(); 184 | try { 185 | value = field.get(null); 186 | } catch (IllegalAccessException|NullPointerException e) { 187 | return String.format("Couldn't access '%s' field value: " + e, name); 188 | } 189 | return String.format("<%s> %s: %s", type, name, String.valueOf(value)); 190 | } 191 | 192 | private static void logFields() { 193 | for (Field field : Build.class.getDeclaredFields()) { 194 | LOG("Build " + logParseField(field)); 195 | } 196 | for (Field field : Build.VERSION.class.getDeclaredFields()) { 197 | LOG("Build.VERSION " + logParseField(field)); 198 | } 199 | } 200 | 201 | static void LOG(String msg) { 202 | Log.d("PIF/Java", msg); 203 | } 204 | 205 | static void append(String a, Certificate c) { 206 | store.put(a, c); 207 | } 208 | 209 | static Certificate retrieve(String a) { 210 | return store.get(a); 211 | } 212 | 213 | static Keybox box(String type) { 214 | return certs.get(type); 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /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 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | 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 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Play Integrity Fork KeyStore Bypass 2 | This fork-fork aim is to bypass the AndroidKeyStore by implementing a similar process software side. 3 | The current implementation provides DEVICE through the classic PIF, while having a test environment that runs the KeyStore bypass in the KeyAttestation app. 4 | At the moment this repository contains: 5 | - Import and parsing of keybox.xml from module folder 6 | - Keypair and its certificate attestation generation through a simplified software implementation of AndroidKeyStore 7 | - Certificate chain retrieval 8 | 9 | The whole implementation provides a valid attestation to the [KeyAttestation app](https://github.com/vvb2060/KeyAttestation). 10 | 11 | *This integration is inspired by chiteroman's BootloaderSpoofer and FrameworkPatch. Parts of the certificate parsing and attestation generation are based on his work* 12 | 13 | ## Lack of time to work on the module 14 | Due to lack of time I am unable to keep working on the implementation. I will provide some open points to expand on the work I did. 15 | 16 | ### Open points 17 | - In order to better grasp the droidguard key requirements, an analysis of the `AlgorithmParameterSpec` provided while initializing the `CustomkeyPairGenerator` should suffice in order to understand the attestation requirements and implement the relative, half implemented and commented, spec handlers. 18 | - Testing could be done with a keybox.xml with associated device parameters, even if the keybox has been invalidated. 19 | - This implementation **has not been tested in droidguard yet**. This means that droidguard could implement checks that validate the KeyPairGenerator, as well as the KeyStoreSpi, through, for example, checking their class name. As well as other checks that could detect any of the current injection methods. 20 | - Remember that each test you do with a valid keybox in droidguard could be detected and result in its future invalidation. I never had the pleasure of testing droidguard with a valid keybox (even if i had multiple prior to the last ban wave) due to not having time to check out the whole `AlgorithmParameterSpec` requested by droidguard, I did only test the current implemented features with key attestation app. 21 | 22 | ## Thoughs on the future 23 | As far as I can tell, even with a bypass working, without a reliable way to retrieve the key from the device you own (prior to RKP), this approach is and will be unsustainable in the long run, due to possible improvements in droidguard detection. 24 | The already existing remote key provisioning system also limits the usage of provisioned keys to a limited time. Expanding on that, emulating the provisioning system will also required reliable extraction from the device TEE that, will be certainly done but, will never be reliable enough for a wide spread use. 25 | 26 | The key point being that google has finally found a way to kick the modding community, custom rom/unlocked bootloader users, out of its ecosystem in a consistent way. 27 | 28 | ## A message to the walled garden keepers 29 | While I do appreciate your dedication and your ways of providing the community with working tools, the way you act shows you more as "entitled" than "helpful". That is at least in my non-existing experience because, even trying, I was unable to have a private conversation with any of you in any way. This could, and probably already is, blocking out useful contributions making this look less like a community effort and more like a personal achievement. 30 | 31 | 32 | # Original Play Integrity Fork README 33 | *PIF forked to be more futureproof and develop more methodically* 34 | 35 | [![GitHub release (latest by date)](https://img.shields.io/github/v/release/osm0sis/PlayIntegrityFork?label=Release&color=blue&style=flat)](https://github.com/osm0sis/PlayIntegrityFork/releases/latest) 36 | [![GitHub Release Date](https://img.shields.io/github/release-date/osm0sis/PlayIntegrityFork?label=Release%20Date&color=brightgreen&style=flat)](https://github.com/osm0sis/PlayIntegrityFork/releases) 37 | [![GitHub Releases](https://img.shields.io/github/downloads/osm0sis/PlayIntegrityFork/latest/total?label=Downloads%20%28Latest%20Release%29&color=blue&style=flat)](https://github.com/osm0sis/PlayIntegrityFork/releases/latest) 38 | [![GitHub All Releases](https://img.shields.io/github/downloads/osm0sis/PlayIntegrityFork/total?label=Total%20Downloads%20%28All%20Releases%29&color=brightgreen&style=flat)](https://github.com/osm0sis/PlayIntegrityFork/releases) 39 | 40 | A Zygisk module which fixes "ctsProfileMatch" (SafetyNet) and "MEETS_DEVICE_INTEGRITY" (Play Integrity). 41 | 42 | To use this module you must have one of the following (latest versions): 43 | 44 | - [Magisk](https://github.com/topjohnwu/Magisk) with Zygisk enabled (and Enforce DenyList enabled if NOT also using [Shamiko](https://github.com/LSPosed/LSPosed.github.io/releases), for best results) 45 | - [KernelSU](https://github.com/tiann/KernelSU) with [Zygisk Next](https://github.com/Dr-TSNG/ZygiskNext) module installed 46 | - [APatch](https://github.com/bmax121/APatch) with [Zygisk Next](https://github.com/Dr-TSNG/ZygiskNext) module installed 47 | 48 | ## About module 49 | 50 | It injects a classes.dex file to modify fields in the android.os.Build class. Also, it creates a hook in the native code to modify system properties. These are spoofed only to Google Play Services' DroidGuard (SafetyNet/Play Integrity) service. 51 | 52 | The purpose of the module is to avoid hardware attestation. 53 | 54 | ## About 'custom.pif.json' file 55 | 56 | You can fill out the included template [example.pif.json](https://raw.githubusercontent.com/osm0sis/PlayIntegrityFork/main/module/example.pif.json) from the module directory (/data/adb/modules/playintegrityfix) then rename it to custom.pif.json to spoof custom values to the GMS unstable process. It will be used instead of any included pif.json (none included currently). 57 | 58 | Note this is just a template with the current suggested defaults, but with this fork you can include as few or as many android.os.Build class fields and Android system properties as needed to pass DEVICE verdict now and in the future if the enforced checks by Play Integrity change. 59 | 60 | As a general rule you can't use values from recent devices due to them only being allowed with full hardware backed attestation. See the Resources below for information and scripts to help find a working fingerprint. 61 | 62 | Older formatted custom.pif.json files from cross-forks and previous releases will be automatically migrated to the latest format. Simply ensure the filename is custom.pif.json and place it in the module directory before upgrading. 63 | 64 | A migration may also be performed manually with `sh migrate.sh` and custom.pif.json in the same directory, or from a file explorer app that supports script execution. 65 | 66 |
67 | Resources 68 | 69 | - FAQ: 70 | - [PIF FAQ](https://xdaforums.com/t/pif-faq.4653307/) - Frequently Asked Questions (READ FIRST!) 71 | 72 | - Guides: 73 | - [How-To Guide](https://xdaforums.com/t/module-play-integrity-fix-safetynet-fix.4607985/post-89189572) - Info to help find build.prop files, then manually create and use a custom.pif.json 74 | - [Complete Noobs' Guide](https://xdaforums.com/t/how-to-search-find-your-own-fingerprints-noob-friendly-a-comprehensive-guide-w-tips-discussion-for-complete-noobs-from-one.4645816/) - A more in-depth basic explainer of the How-To Guide above 75 | - [UI Workflow Guide](https://xdaforums.com/t/pixelflasher-a-gui-tool-for-flashing-updating-rooting-managing-pixel-phones.4415453/post-87412305) - Build/find, edit, and test custom.pif.json using PixelFlasher on PC 76 | - [Tasker PIF Testing Helper](https://xdaforums.com/t/pif-testing-helper-tasker-profile-for-testing-fingerprints.4644827/) - Test custom.pif.json using Tasker on device 77 | 78 | - Scripts: 79 | - [gen_pif_custom.sh](https://xdaforums.com/t/tools-zips-scripts-osm0sis-odds-and-ends-multiple-devices-platforms.2239421/post-89173470) - Script to generate a custom.pif.json from device dump build.prop files 80 | - [autopif.sh](https://xdaforums.com/t/module-play-integrity-fix-safetynet-fix.4607985/post-89233630) - Script to extract the latest working Xiaomi.eu fingerprint (though frequently banned) to test an initial setup 81 | - [install-random-fp.sh](https://xdaforums.com/t/script-for-randomly-installing-custom-device-fingerprints.4647408/) - Script to randomly switch between multiple working fingerprints found by the user 82 | 83 |
84 | 85 | ## About 'custom.app_replace.list' file 86 | 87 | You can customize the included default [example.app_replace.list](https://raw.githubusercontent.com/osm0sis/PlayIntegrityFork/main/module/example.app_replace.list) from the module directory (/data/adb/modules/playintegrityfix) then rename it to custom.app_replace.list to systemlessly replace any additional conflicting custom ROM spoof injection app paths to disable them. 88 | 89 | ## Troubleshooting 90 | 91 | Make sure Google Play Services (com.google.android.gms) is NOT on the Magisk DenyList if Enforce DenyList is enabled since this interferes with the module; the module does prevent this using scripts but it only happens once during each reboot. 92 | 93 | ### Failing BASIC verdict 94 | 95 | If you are failing basicIntegrity (SafetyNet) or MEETS_BASIC_INTEGRITY (Play Integrity) something is wrong in your setup. Recommended steps in order to find the problem: 96 | 97 | - Disable all modules except this one 98 | - Try a different (ideally known working) custom.pif.json 99 | 100 | Note: Some modules which modify system (e.g. Xposed) can trigger DroidGuard detections, as can any which hook GMS processes (e.g. custom fonts). 101 | 102 | ### Failing DEVICE verdict (on KernelSU/APatch) 103 | 104 | - Disable Zygisk Next 105 | - Reboot 106 | - Enable Zygisk Next 107 | - Reboot again 108 | 109 | ### Failing DEVICE verdict (on custom kernel/ROM) 110 | 111 | - Check the kernel release string with command `adb shell uname -r` or `uname -r` 112 | - If it's on the [Known Banned Kernel List](https://xdaforums.com/t/module-play-integrity-fix-safetynet-fix.4607985/post-89308909) then inform your kernel developer/ROM maintainer to remove their branding for their next build 113 | - You may also try a different custom kernel, or go back to the default kernel for your ROM, if available/possible 114 | 115 | ### Play Protect/Store Certification and Google Wallet Tap To Pay Setup Security Requirements 116 | 117 | Follow these steps: 118 | 119 | - Reflash the module in your root manager app 120 | - Clear Google Wallet (com.google.android.apps.walletnfcrel) and/or Google Pay (com.google.android.apps.nbu.paisa.user) cache, if you have them installed 121 | - Clear Google Play Store (com.android.vending) cache and data 122 | - Clear Google Play Services (com.google.android.gms) cache and data, or, optionally skip clearing data and wait some time (~24h) for it to resolve on its own 123 | - Reboot 124 | 125 | Note: Clearing Google Play Services app ***data*** will then require you to reset any WearOS devices paired to your device. 126 | 127 | ### Read module logs 128 | 129 | You can read module logs using one of these commands directly after boot: 130 | 131 | `adb shell "logcat | grep 'PIF/'"` or `su -c "logcat | grep 'PIF/'"` 132 | 133 | Add a "verboseLogs" entry with a value of "0", "1", "2", "3" or "100" to your custom.pif.json to enable higher logging levels; "100" will dump all Build fields, and all the system properties that DroidGuard is checking. Adding the entry can also be done using the migration script with the `sh migrate.sh --force --advanced` or `sh migrate.sh -f -a` command. 134 | 135 | ## Can this module pass MEETS_STRONG_INTEGRITY? 136 | 137 | No. 138 | 139 | ## About Play Integrity (SafetyNet is deprecated) 140 | 141 | [Play Integrity API](https://xdaforums.com/t/info-play-integrity-api-replacement-for-safetynet.4479337/) - FAQ/information about PI (Play Integrity) replacing SN (SafetyNet) 142 | 143 | ## Credits 144 | 145 | Module scripts were adapted from those of kdrag0n/Displax's Universal SafetyNet Fix (USNF) module, please see the commit history of [Displax's USNF Fork](https://github.com/Displax/safetynet-fix/tree/dev/magisk) for proper attribution. 146 | -------------------------------------------------------------------------------- /app/src/main/cpp/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "zygisk.hpp" 6 | #include "json.hpp" 7 | #include "dobby.h" 8 | 9 | #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "PIF/Native", __VA_ARGS__) 10 | 11 | #define DEX_FILE_PATH "/data/adb/modules/playintegrityfix/classes.dex" 12 | 13 | #define JSON_FILE_PATH "/data/adb/modules/playintegrityfix/pif.json" 14 | #define CUSTOM_JSON_FILE_PATH "/data/adb/modules/playintegrityfix/custom.pif.json" 15 | #define KEYBOX_FILE_PATH "/data/adb/modules/playintegrityfix/keybox.xml" 16 | 17 | static int verboseLogs = 0; 18 | 19 | static std::map jsonProps; 20 | 21 | typedef void (*T_Callback)(void *, const char *, const char *, uint32_t); 22 | 23 | static std::map callbacks; 24 | 25 | static void modify_callback(void *cookie, const char *name, const char *value, uint32_t serial) { 26 | if (cookie == nullptr || name == nullptr || value == nullptr || !callbacks.contains(cookie)) return; 27 | 28 | const char *oldValue = value; 29 | 30 | std::string prop(name); 31 | 32 | // Spoof specific property values 33 | if (prop == "init.svc.adbd") { 34 | value = "stopped"; 35 | } else if (prop == "sys.usb.state") { 36 | value = "mtp"; 37 | } 38 | 39 | if (jsonProps.count(prop)) { 40 | // Exact property match 41 | value = jsonProps[prop].c_str(); 42 | } else { 43 | // Leading * wildcard property match 44 | for (const auto &p: jsonProps) { 45 | if (p.first.starts_with("*") && prop.ends_with(p.first.substr(1))) { 46 | value = p.second.c_str(); 47 | break; 48 | } 49 | } 50 | } 51 | 52 | if (oldValue == value) { 53 | if (verboseLogs > 99) LOGD("[%s]: %s (unchanged)", name, oldValue); 54 | } else { 55 | LOGD("[%s]: %s -> %s", name, oldValue, value); 56 | } 57 | 58 | return callbacks[cookie](cookie, name, value, serial); 59 | } 60 | 61 | static void (*o_system_property_read_callback)(const prop_info *, T_Callback, void *); 62 | 63 | static void my_system_property_read_callback(const prop_info *pi, T_Callback callback, void *cookie) { 64 | if (pi == nullptr || callback == nullptr || cookie == nullptr) { 65 | return o_system_property_read_callback(pi, callback, cookie); 66 | } 67 | callbacks[cookie] = callback; 68 | return o_system_property_read_callback(pi, modify_callback, cookie); 69 | } 70 | 71 | static void doHook() { 72 | void *handle = DobbySymbolResolver(nullptr, "__system_property_read_callback"); 73 | if (handle == nullptr) { 74 | LOGD("Couldn't find '__system_property_read_callback' handle"); 75 | return; 76 | } 77 | LOGD("Found '__system_property_read_callback' handle at %p", handle); 78 | DobbyHook(handle, reinterpret_cast(my_system_property_read_callback), 79 | reinterpret_cast(&o_system_property_read_callback)); 80 | } 81 | 82 | class PlayIntegrityFix : public zygisk::ModuleBase { 83 | public: 84 | void onLoad(zygisk::Api *api, JNIEnv *env) override { 85 | this->api = api; 86 | this->env = env; 87 | } 88 | 89 | void preAppSpecialize(zygisk::AppSpecializeArgs *args) override { 90 | bool isGms = false, isGmsUnstable = false, isKeyAttestation = false; 91 | 92 | auto rawProcess = env->GetStringUTFChars(args->nice_name, nullptr); 93 | auto rawDir = env->GetStringUTFChars(args->app_data_dir, nullptr); 94 | 95 | // Prevent crash on apps with no data dir 96 | if (rawDir == nullptr) { 97 | env->ReleaseStringUTFChars(args->nice_name, rawProcess); 98 | api->setOption(zygisk::DLCLOSE_MODULE_LIBRARY); 99 | return; 100 | } 101 | 102 | std::string_view process(rawProcess); 103 | std::string_view dir(rawDir); 104 | 105 | isGms = dir.ends_with("/com.google.android.gms"); 106 | isGmsUnstable = process == "com.google.android.gms.unstable"; 107 | // TODO hex3l: remove keyattestation app from checks 108 | isKeyAttestation = process == "io.github.vvb2060.keyattestation"; 109 | 110 | env->ReleaseStringUTFChars(args->nice_name, rawProcess); 111 | env->ReleaseStringUTFChars(args->app_data_dir, rawDir); 112 | // TODO hex3l: remove keyattestation app from checks 113 | if (isKeyAttestation) LOGD("Found KeyAttestation APP"); 114 | if (!isKeyAttestation) { 115 | if (!isGms) { 116 | api->setOption(zygisk::DLCLOSE_MODULE_LIBRARY); 117 | return; 118 | } 119 | 120 | // We are in GMS now, force unmount 121 | api->setOption(zygisk::FORCE_DENYLIST_UNMOUNT); 122 | 123 | if (!isGmsUnstable) { 124 | api->setOption(zygisk::DLCLOSE_MODULE_LIBRARY); 125 | return; 126 | } 127 | } 128 | 129 | std::vector jsonVector; 130 | std::vector xmlVector; 131 | long dexSize = 0, jsonSize = 0, xmlSize = 0; 132 | 133 | int fd = api->connectCompanion(); 134 | 135 | read(fd, &dexSize, sizeof(long)); 136 | read(fd, &jsonSize, sizeof(long)); 137 | read(fd, &xmlSize, sizeof(long)); 138 | 139 | if (dexSize < 1) { 140 | close(fd); 141 | LOGD("Couldn't read dex file"); 142 | api->setOption(zygisk::DLCLOSE_MODULE_LIBRARY); 143 | return; 144 | } 145 | 146 | if (jsonSize < 1) { 147 | close(fd); 148 | LOGD("Couldn't read json file"); 149 | api->setOption(zygisk::DLCLOSE_MODULE_LIBRARY); 150 | return; 151 | } 152 | 153 | if (xmlSize < 1) { 154 | close(fd); 155 | LOGD("Couldn't read xml file"); 156 | api->setOption(zygisk::DLCLOSE_MODULE_LIBRARY); 157 | return; 158 | } 159 | 160 | LOGD("Read from file descriptor for 'dex' -> %ld bytes", dexSize); 161 | LOGD("Read from file descriptor for 'json' -> %ld bytes", jsonSize); 162 | LOGD("Read from file descriptor for 'xml' -> %ld bytes", xmlSize); 163 | 164 | dexVector.resize(dexSize); 165 | read(fd, dexVector.data(), dexSize); 166 | 167 | jsonVector.resize(jsonSize); 168 | read(fd, jsonVector.data(), jsonSize); 169 | 170 | xmlVector.resize(xmlSize); 171 | read(fd, xmlVector.data(), xmlSize); 172 | 173 | close(fd); 174 | 175 | std::string jsonString(jsonVector.cbegin(), jsonVector.cend()); 176 | json = nlohmann::json::parse(jsonString, nullptr, false, true); 177 | 178 | std::string xmlString(xmlVector.begin(), xmlVector.end()); 179 | xml = xmlString; 180 | 181 | jsonVector.clear(); 182 | jsonString.clear(); 183 | } 184 | 185 | void postAppSpecialize(const zygisk::AppSpecializeArgs *args) override { 186 | if (dexVector.empty() || json.empty() || xml.empty()) return; 187 | 188 | readJson(); 189 | doHook(); 190 | inject(); 191 | 192 | dexVector.clear(); 193 | json.clear(); 194 | xml.clear(); 195 | } 196 | 197 | void preServerSpecialize(zygisk::ServerSpecializeArgs *args) override { 198 | api->setOption(zygisk::DLCLOSE_MODULE_LIBRARY); 199 | } 200 | 201 | private: 202 | zygisk::Api *api = nullptr; 203 | JNIEnv *env = nullptr; 204 | std::vector dexVector; 205 | std::string xml; 206 | nlohmann::json json; 207 | 208 | void readJson() { 209 | LOGD("JSON contains %d keys!", static_cast(json.size())); 210 | 211 | // Verbose logging if verboseLogs with level number is present 212 | if (json.contains("verboseLogs")) { 213 | if (!json["verboseLogs"].is_null() && json["verboseLogs"].is_string() && json["verboseLogs"] != "") { 214 | verboseLogs = stoi(json["verboseLogs"].get()); 215 | if (verboseLogs > 0) LOGD("Verbose logging (level %d) enabled!", verboseLogs); 216 | } else { 217 | LOGD("Error parsing verboseLogs!"); 218 | } 219 | json.erase("verboseLogs"); 220 | } 221 | 222 | std::vector eraseKeys; 223 | for (auto &jsonList: json.items()) { 224 | if (verboseLogs > 1) LOGD("Parsing %s", jsonList.key().c_str()); 225 | if (jsonList.key().find_first_of("*.") != std::string::npos) { 226 | // Name contains . or * (wildcard) so assume real property name 227 | if (!jsonList.value().is_null() && jsonList.value().is_string()) { 228 | if (jsonList.value() == "") { 229 | LOGD("%s is empty, skipping", jsonList.key().c_str()); 230 | } else { 231 | if (verboseLogs > 0) LOGD("Adding '%s' to properties list", jsonList.key().c_str()); 232 | jsonProps[jsonList.key()] = jsonList.value(); 233 | } 234 | } else { 235 | LOGD("Error parsing %s!", jsonList.key().c_str()); 236 | } 237 | eraseKeys.push_back(jsonList.key()); 238 | } 239 | } 240 | // Remove properties from parsed JSON 241 | for (auto key: eraseKeys) { 242 | if (json.contains(key)) json.erase(key); 243 | } 244 | } 245 | 246 | void inject() { 247 | LOGD("JNI: Getting system classloader"); 248 | auto clClass = env->FindClass("java/lang/ClassLoader"); 249 | auto getSystemClassLoader = env->GetStaticMethodID(clClass, "getSystemClassLoader", "()Ljava/lang/ClassLoader;"); 250 | auto systemClassLoader = env->CallStaticObjectMethod(clClass, getSystemClassLoader); 251 | 252 | LOGD("JNI: Creating module classloader"); 253 | auto dexClClass = env->FindClass("dalvik/system/InMemoryDexClassLoader"); 254 | auto dexClInit = env->GetMethodID(dexClClass, "", "(Ljava/nio/ByteBuffer;Ljava/lang/ClassLoader;)V"); 255 | auto buffer = env->NewDirectByteBuffer(dexVector.data(), static_cast(dexVector.size())); 256 | auto dexCl = env->NewObject(dexClClass, dexClInit, buffer, systemClassLoader); 257 | 258 | LOGD("JNI: Loading module class"); 259 | auto loadClass = env->GetMethodID(clClass, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;"); 260 | auto entryClassName = env->NewStringUTF("es.chiteroman.playintegrityfix.EntryPoint"); 261 | auto entryClassObj = env->CallObjectMethod(dexCl, loadClass, entryClassName); 262 | 263 | auto entryClass = (jclass) entryClassObj; 264 | 265 | LOGD("JNI: Sending JSON"); 266 | auto receiveJson = env->GetStaticMethodID(entryClass, "receiveJson", "(Ljava/lang/String;)V"); 267 | auto jsonJavaStr = env->NewStringUTF(json.dump().c_str()); 268 | env->CallStaticVoidMethod(entryClass, receiveJson, jsonJavaStr); 269 | 270 | LOGD("JNI: Sending XML"); 271 | auto receiveXml = env->GetStaticMethodID(entryClass, "receiveXml", "(Ljava/lang/String;)V"); 272 | auto xmlJavaString = env->NewStringUTF(xml.c_str()); 273 | env->CallStaticVoidMethod(entryClass, receiveXml, xmlJavaString); 274 | 275 | LOGD("JNI: Calling init"); 276 | auto entryInit = env->GetStaticMethodID(entryClass, "init", "(I)V"); 277 | env->CallStaticVoidMethod(entryClass, entryInit, verboseLogs); 278 | } 279 | }; 280 | 281 | static void companion(int fd) { 282 | long dexSize = 0, jsonSize = 0, xmlSize = 0; 283 | std::vector dexVector, jsonVector, xmlVector; 284 | 285 | FILE *dex = fopen(DEX_FILE_PATH, "rb"); 286 | 287 | if (dex) { 288 | fseek(dex, 0, SEEK_END); 289 | dexSize = ftell(dex); 290 | fseek(dex, 0, SEEK_SET); 291 | 292 | dexVector.resize(dexSize); 293 | fread(dexVector.data(), 1, dexSize, dex); 294 | 295 | fclose(dex); 296 | } 297 | 298 | FILE *json = fopen(CUSTOM_JSON_FILE_PATH, "r"); 299 | if (!json) 300 | json = fopen(JSON_FILE_PATH, "r"); 301 | 302 | if (json) { 303 | fseek(json, 0, SEEK_END); 304 | jsonSize = ftell(json); 305 | fseek(json, 0, SEEK_SET); 306 | 307 | jsonVector.resize(jsonSize); 308 | fread(jsonVector.data(), 1, jsonSize, json); 309 | 310 | fclose(json); 311 | } 312 | 313 | FILE *xml = fopen(KEYBOX_FILE_PATH, "r"); 314 | 315 | if (xml) { 316 | fseek(xml, 0, SEEK_END); 317 | xmlSize = ftell(xml); 318 | fseek(xml, 0, SEEK_SET); 319 | 320 | xmlVector.resize(xmlSize); 321 | fread(xmlVector.data(), 1, xmlSize, xml); 322 | 323 | fclose(xml); 324 | } 325 | 326 | write(fd, &dexSize, sizeof(long)); 327 | write(fd, &jsonSize, sizeof(long)); 328 | write(fd, &xmlSize, sizeof(long)); 329 | 330 | write(fd, dexVector.data(), dexSize); 331 | write(fd, jsonVector.data(), jsonSize); 332 | write(fd, xmlVector.data(), xmlSize); 333 | 334 | dexVector.clear(); 335 | jsonVector.clear(); 336 | } 337 | 338 | REGISTER_ZYGISK_MODULE(PlayIntegrityFix) 339 | 340 | REGISTER_ZYGISK_COMPANION(companion) 341 | -------------------------------------------------------------------------------- /app/src/main/cpp/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 | -------------------------------------------------------------------------------- /app/src/main/java/es/chiteroman/playintegrityfix/CustomKeyStoreKeyPairGeneratorSpi.java: -------------------------------------------------------------------------------- 1 | package es.chiteroman.playintegrityfix; 2 | 3 | import android.os.Build; 4 | import android.security.keystore.KeyGenParameterSpec; 5 | import android.security.keystore.KeyProperties; 6 | 7 | import org.bouncycastle.asn1.ASN1Boolean; 8 | import org.bouncycastle.asn1.ASN1Encodable; 9 | import org.bouncycastle.asn1.ASN1Enumerated; 10 | import org.bouncycastle.asn1.ASN1Integer; 11 | import org.bouncycastle.asn1.ASN1ObjectIdentifier; 12 | import org.bouncycastle.asn1.ASN1OctetString; 13 | import org.bouncycastle.asn1.ASN1Sequence; 14 | import org.bouncycastle.asn1.DERNull; 15 | import org.bouncycastle.asn1.DEROctetString; 16 | import org.bouncycastle.asn1.DERSequence; 17 | import org.bouncycastle.asn1.DERSet; 18 | import org.bouncycastle.asn1.DERTaggedObject; 19 | import org.bouncycastle.asn1.x500.X500Name; 20 | import org.bouncycastle.asn1.x509.Extension; 21 | import org.bouncycastle.asn1.x509.KeyUsage; 22 | import org.bouncycastle.cert.X509CertificateHolder; 23 | import org.bouncycastle.cert.X509v3CertificateBuilder; 24 | import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; 25 | import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; 26 | import org.bouncycastle.jce.provider.BouncyCastleProvider; 27 | import org.bouncycastle.operator.ContentSigner; 28 | import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; 29 | 30 | import java.nio.charset.StandardCharsets; 31 | import java.security.KeyPair; 32 | import java.security.KeyPairGenerator; 33 | import java.security.KeyPairGeneratorSpi; 34 | import java.security.ProviderException; 35 | import java.security.SecureRandom; 36 | import java.security.Security; 37 | import java.security.spec.AlgorithmParameterSpec; 38 | import java.security.spec.ECGenParameterSpec; 39 | import java.security.spec.RSAKeyGenParameterSpec; 40 | import java.util.Locale; 41 | import java.util.Objects; 42 | 43 | public class CustomKeyStoreKeyPairGeneratorSpi extends KeyPairGeneratorSpi { 44 | 45 | private static final int ATTESTATION_APPLICATION_ID_PACKAGE_INFOS_INDEX = 0; 46 | private static final int ATTESTATION_APPLICATION_ID_SIGNATURE_DIGESTS_INDEX = 1; 47 | private static final int ATTESTATION_PACKAGE_INFO_PACKAGE_NAME_INDEX = 0; 48 | private static final int ATTESTATION_PACKAGE_INFO_VERSION_INDEX = 1; 49 | 50 | final String KEYSTORE = "AndroidKeyStore"; 51 | private final String requestedAlgo; 52 | private KeyGenParameterSpec params; 53 | 54 | private KeyPairGenerator baseGenerator; 55 | public static final class RSA extends CustomKeyStoreKeyPairGeneratorSpi { 56 | public RSA() { 57 | super(KeyProperties.KEY_ALGORITHM_RSA); 58 | } 59 | } 60 | 61 | public static final class EC extends CustomKeyStoreKeyPairGeneratorSpi { 62 | public EC() { 63 | super(KeyProperties.KEY_ALGORITHM_EC); 64 | } 65 | } 66 | protected CustomKeyStoreKeyPairGeneratorSpi(String algo){ 67 | requestedAlgo = algo; 68 | } 69 | 70 | @Override 71 | public void initialize(int keysize, SecureRandom random) { 72 | // do nothing = ok 73 | try { 74 | baseGenerator = KeyPairGenerator.getInstance("OLD" + requestedAlgo, Security.getProvider(KEYSTORE)); 75 | baseGenerator.initialize(keysize, random); 76 | } catch (Exception e) { 77 | EntryPoint.LOG("Failed to load OLD KeyPairGen: " + e); 78 | } 79 | } 80 | 81 | @Override 82 | public void initialize(AlgorithmParameterSpec params, SecureRandom random) { 83 | this.params = (KeyGenParameterSpec) params; 84 | try { 85 | baseGenerator = KeyPairGenerator.getInstance("OLD" + requestedAlgo, Security.getProvider(KEYSTORE)); 86 | baseGenerator.initialize(params, random); 87 | } catch (Exception e) { 88 | EntryPoint.LOG("Failed to load OLD KeyPairGen: " + e); 89 | } 90 | } 91 | 92 | @Override 93 | public KeyPair generateKeyPair() { 94 | for (StackTraceElement e : Thread.currentThread().getStackTrace()) { 95 | // TODO hex3l: bypass keystore only for droidguard 96 | // currently only in attestation test app 97 | if (e.getClassName().toLowerCase(Locale.ROOT).contains("vvb2060")) { 98 | try { 99 | EntryPoint.LOG("Requested KeyPair with alias: " + params.getKeystoreAlias()); 100 | KeyPair rootKP; 101 | KeyPair kp; 102 | X500Name issuer; 103 | int size = params.getKeySize(); 104 | if(size == -1) size = getKeySizeFromCurve(); 105 | 106 | if (Objects.equals(requestedAlgo, KeyProperties.KEY_ALGORITHM_EC)) { 107 | EntryPoint.LOG("GENERATING EC KEYPAIR OF SIZE " + size); 108 | kp = buildECKeyPair(); 109 | Keybox k = EntryPoint.box("ecdsa"); 110 | rootKP = k.keypair(); 111 | issuer = k.certificateChainSubject().getFirst(); 112 | } else { 113 | // TODO hex3l: validate process for RSA 114 | kp = buildRSAKeyPair(); 115 | Keybox k = EntryPoint.box("rsa"); 116 | rootKP = k.keypair(); 117 | issuer = k.certificateChainSubject().getFirst(); 118 | } 119 | 120 | X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, params.getCertificateSerialNumber(), params.getCertificateNotBefore(), params.getCertificateNotAfter(), new X500Name(params.getCertificateSubject().getName()), kp.getPublic()); 121 | 122 | KeyUsage keyUsage = new KeyUsage(KeyUsage.keyCertSign); 123 | certBuilder.addExtension(Extension.keyUsage, true, keyUsage); 124 | 125 | certBuilder.addExtension(createExtension(size)); 126 | 127 | // TODO hex3l: validate the process for RSA 128 | ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withECDSA").build(rootKP.getPrivate()); 129 | 130 | X509CertificateHolder certHolder = certBuilder.build(contentSigner); 131 | 132 | EntryPoint.append(params.getKeystoreAlias(), new JcaX509CertificateConverter().getCertificate(certHolder)); 133 | EntryPoint.LOG("Successfully generated X500 Cert for alias: " + params.getKeystoreAlias()); 134 | 135 | return kp; 136 | } catch (Throwable t) { 137 | EntryPoint.LOG("Error while generating KeyPair:" + t); 138 | throw new ProviderException("Failed to generate key pair."); 139 | } 140 | } 141 | } 142 | return baseGenerator.generateKeyPair(); 143 | } 144 | 145 | private Extension createExtension(int size) { 146 | try { 147 | SecureRandom random = new SecureRandom(); 148 | 149 | byte[] bytes1 = new byte[32]; 150 | byte[] bytes2 = new byte[32]; 151 | 152 | random.nextBytes(bytes1); 153 | random.nextBytes(bytes2); 154 | 155 | ASN1Encodable[] rootOfTrustEncodables = {new DEROctetString(bytes1), ASN1Boolean.TRUE, new ASN1Enumerated(0), new DEROctetString(bytes2)}; 156 | 157 | ASN1Sequence rootOfTrustSeq = new DERSequence(rootOfTrustEncodables); 158 | 159 | // TODO hex3l: validate that SIGN is the only required or create a parser 160 | ASN1Integer[] purposesArray = { 161 | new ASN1Integer(2) //params.getPurposes() 162 | }; 163 | 164 | var Apurpose = new DERSet(purposesArray); 165 | var Aalgorithm = new ASN1Integer(getAlgorithm()); 166 | var AkeySize = new ASN1Integer(size); 167 | var Adigest = new DERSet(getDigests()); 168 | var AecCurve = new ASN1Integer(getEcCurve()); 169 | var AnoAuthRequired = DERNull.INSTANCE; 170 | 171 | // TODO hex3l: add device properties to attestation 172 | ASN1Encodable[] deviceProperties; 173 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { 174 | if (params.isDevicePropertiesAttestationIncluded()) { 175 | var platformReportedBrand = new DEROctetString(getSystemProperty(Build.BRAND).getBytes()); 176 | var platformReportedDevice = new DEROctetString(getSystemProperty(Build.DEVICE).getBytes()); 177 | var platformReportedProduct = new DEROctetString(getSystemProperty(Build.PRODUCT).getBytes()); 178 | var platformReportedManufacturer = new DEROctetString(getSystemProperty(Build.MANUFACTURER).getBytes()); 179 | var platformReportedModel = new DEROctetString(getSystemProperty(Build.MODEL).getBytes()); 180 | deviceProperties = new ASN1Encodable[]{platformReportedBrand, platformReportedDevice, platformReportedProduct, platformReportedManufacturer, platformReportedModel}; 181 | } 182 | } 183 | 184 | // To be loaded 185 | var AosVersion = new ASN1Integer(130000); 186 | var AosPatchLevel = new ASN1Integer(202401); 187 | 188 | // TODO hex3l: add applicationID to attestation 189 | // var AapplicationID = createApplicationId(); 190 | var AbootPatchlevel = new ASN1Integer(20231101); 191 | var AvendorPatchLevel = new ASN1Integer(20231101); 192 | 193 | var AcreationDateTime = new ASN1Integer(System.currentTimeMillis()); 194 | var Aorigin = new ASN1Integer(0); 195 | 196 | var purpose = new DERTaggedObject(true, 1, Apurpose); 197 | var algorithm = new DERTaggedObject(true, 2, Aalgorithm); 198 | var keySize = new DERTaggedObject(true, 3, AkeySize); 199 | var digest = new DERTaggedObject(true, 5, Adigest); 200 | var ecCurve = new DERTaggedObject(true, 10, AecCurve); 201 | var noAuthRequired = new DERTaggedObject(true, 503, AnoAuthRequired); 202 | var creationDateTime = new DERTaggedObject(true, 701, AcreationDateTime); 203 | var origin = new DERTaggedObject(true, 702, Aorigin); 204 | var rootOfTrust = new DERTaggedObject(true, 704, rootOfTrustSeq); 205 | var osVersion = new DERTaggedObject(true, 705, AosVersion); 206 | var osPatchLevel = new DERTaggedObject(true, 706, AosPatchLevel); 207 | // TODO hex3l: add applicationID to attestation 208 | // var applicationID = new DERTaggedObject(true, 709, AapplicationID); 209 | var vendorPatchLevel = new DERTaggedObject(true, 718, AvendorPatchLevel); 210 | var bootPatchLevel = new DERTaggedObject(true, 719, AbootPatchlevel); 211 | 212 | ASN1Encodable[] teeEnforcedEncodables = {purpose, algorithm, keySize, digest, ecCurve, noAuthRequired, creationDateTime, origin, rootOfTrust, osVersion, osPatchLevel, vendorPatchLevel, bootPatchLevel}; 213 | 214 | ASN1Integer attestationVersion = new ASN1Integer(4); 215 | ASN1Enumerated attestationSecurityLevel = new ASN1Enumerated(1); 216 | ASN1Integer keymasterVersion = new ASN1Integer(41); 217 | ASN1Enumerated keymasterSecurityLevel = new ASN1Enumerated(1); 218 | ASN1OctetString attestationChallenge = new DEROctetString(params.getAttestationChallenge()); 219 | ASN1OctetString uniqueId = new DEROctetString("".getBytes()); 220 | ASN1Sequence softwareEnforced = new DERSequence(); 221 | ASN1Sequence teeEnforced = new DERSequence(teeEnforcedEncodables); 222 | 223 | ASN1Encodable[] keyDescriptionEncodables = {attestationVersion, attestationSecurityLevel, keymasterVersion, keymasterSecurityLevel, attestationChallenge, uniqueId, softwareEnforced, teeEnforced}; 224 | 225 | ASN1Sequence keyDescriptionHackSeq = new DERSequence(keyDescriptionEncodables); 226 | 227 | ASN1OctetString keyDescriptionOctetStr = new DEROctetString(keyDescriptionHackSeq); 228 | 229 | return new Extension(new ASN1ObjectIdentifier("1.3.6.1.4.1.11129.2.1.17"), false, keyDescriptionOctetStr); 230 | 231 | } catch (Throwable t) { 232 | EntryPoint.LOG(t.toString()); 233 | } 234 | return null; 235 | } 236 | 237 | private ASN1Encodable[] getDigests() { 238 | String[] digests = params.getDigests(); 239 | ASN1Encodable[] result = new ASN1Encodable[digests.length]; 240 | for (int i = 0; i < digests.length; i++) { 241 | String digest = digests[i]; 242 | int d; 243 | switch (digest){ 244 | case KeyProperties.DIGEST_MD5 -> d = 1; 245 | case KeyProperties.DIGEST_SHA1 -> d = 2; 246 | case KeyProperties.DIGEST_SHA224 -> d = 3; 247 | case KeyProperties.DIGEST_SHA256 -> d = 4; 248 | case KeyProperties.DIGEST_SHA384 -> d = 5; 249 | case KeyProperties.DIGEST_SHA512 -> d = 6; 250 | default -> d = 0; 251 | } 252 | result[i] = new ASN1Integer(d); 253 | } 254 | return result; 255 | } 256 | 257 | // TODO hex3l: improve compatibility 258 | private int getEcCurve() { 259 | String name = ((ECGenParameterSpec) params.getAlgorithmParameterSpec()).getName(); 260 | int res; 261 | switch (name){ 262 | case "secp256r1" -> res = 1; 263 | default -> res = 0; 264 | } 265 | return res; 266 | } 267 | 268 | // TODO hex3l: improve compatibility, view commented code bottom of file 269 | private int getKeySizeFromCurve() { 270 | String name = ((ECGenParameterSpec) params.getAlgorithmParameterSpec()).getName(); 271 | int res; 272 | switch (name){ 273 | case "secp256r1" -> res = 256; 274 | default -> res = -1; 275 | } 276 | return res; 277 | } 278 | 279 | // TODO hex3l: improve compatibility 280 | private int getAlgorithm() 281 | { 282 | return switch (requestedAlgo) { 283 | case KeyProperties.KEY_ALGORITHM_EC -> 3; 284 | default -> 0; 285 | }; 286 | } 287 | 288 | private KeyPair buildECKeyPair() throws Exception { 289 | ECGenParameterSpec spec = ((ECGenParameterSpec) params.getAlgorithmParameterSpec()); 290 | Security.addProvider(new BouncyCastleProvider()); 291 | KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME); 292 | kpg.initialize(spec); 293 | return kpg.generateKeyPair(); 294 | } 295 | 296 | private KeyPair buildRSAKeyPair() throws Exception { 297 | RSAKeyGenParameterSpec spec = ((RSAKeyGenParameterSpec) Objects.requireNonNull(params.getAlgorithmParameterSpec())); 298 | Security.addProvider(new BouncyCastleProvider()); 299 | KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); 300 | kpg.initialize(spec); 301 | return kpg.generateKeyPair(); 302 | } 303 | 304 | 305 | ASN1Sequence createApplicationId(String packageName, int version, byte[] signatureDigests) { 306 | ASN1Encodable[] packageInfoAsn1Array = new ASN1Encodable[2]; 307 | packageInfoAsn1Array[ATTESTATION_PACKAGE_INFO_PACKAGE_NAME_INDEX] = 308 | new DEROctetString(packageName.getBytes(StandardCharsets.UTF_8)); 309 | packageInfoAsn1Array[ATTESTATION_PACKAGE_INFO_VERSION_INDEX] = new ASN1Integer(version); 310 | 311 | 312 | 313 | ASN1Encodable[] applicationIdAsn1Array = new ASN1Encodable[2]; 314 | applicationIdAsn1Array[ATTESTATION_APPLICATION_ID_PACKAGE_INFOS_INDEX] = 315 | new DERSet(packageInfoAsn1Array); 316 | 317 | applicationIdAsn1Array[ATTESTATION_APPLICATION_ID_SIGNATURE_DIGESTS_INDEX] = 318 | new DERSet(new DEROctetString(signatureDigests)); 319 | 320 | return new DERSequence(applicationIdAsn1Array); 321 | } 322 | 323 | public String getSystemProperty(String key) { 324 | String value = null; 325 | 326 | try { 327 | value = (String) Class.forName("android.os.SystemProperties") 328 | .getMethod("get", String.class).invoke(null, key); 329 | } catch (Exception e) { 330 | e.printStackTrace(); 331 | } 332 | 333 | return value; 334 | } 335 | } 336 | 337 | /* 338 | // Aliases for NIST P-224 339 | SUPPORTED_EC_CURVE_NAME_TO_SIZE.put("p-224", 224); 340 | SUPPORTED_EC_CURVE_NAME_TO_SIZE.put("secp224r1", 224); 341 | 342 | // Aliases for NIST P-256 343 | SUPPORTED_EC_CURVE_NAME_TO_SIZE.put("p-256", 256); 344 | SUPPORTED_EC_CURVE_NAME_TO_SIZE.put("secp256r1", 256); 345 | SUPPORTED_EC_CURVE_NAME_TO_SIZE.put("prime256v1", 256); 346 | // Aliases for Curve 25519 347 | SUPPORTED_EC_CURVE_NAME_TO_SIZE.put(CURVE_X_25519.toLowerCase(Locale.US), 256); 348 | SUPPORTED_EC_CURVE_NAME_TO_SIZE.put(CURVE_ED_25519.toLowerCase(Locale.US), 256); 349 | 350 | // Aliases for NIST P-384 351 | SUPPORTED_EC_CURVE_NAME_TO_SIZE.put("p-384", 384); 352 | SUPPORTED_EC_CURVE_NAME_TO_SIZE.put("secp384r1", 384); 353 | 354 | // Aliases for NIST P-521 355 | SUPPORTED_EC_CURVE_NAME_TO_SIZE.put("p-521", 521); 356 | SUPPORTED_EC_CURVE_NAME_TO_SIZE.put("secp521r1", 521); 357 | 358 | */ 359 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------