mirror of
https://github.com/revanced/revanced-cli.git
synced 2025-01-06 01:05:50 +01:00
Merge pull request #24 from revanced/non-root
feat: support `non-root` installation
This commit is contained in:
commit
ee4a83bef9
@ -9,6 +9,7 @@ group = "app.revanced"
|
|||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
|
google()
|
||||||
mavenLocal()
|
mavenLocal()
|
||||||
maven {
|
maven {
|
||||||
url = uri("https://maven.pkg.github.com/revanced/multidexlib2")
|
url = uri("https://maven.pkg.github.com/revanced/multidexlib2")
|
||||||
@ -24,11 +25,11 @@ repositories {
|
|||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation("org.jetbrains.kotlin:kotlin-stdlib:1.6.21")
|
implementation("org.jetbrains.kotlin:kotlin-stdlib:1.6.21")
|
||||||
implementation("app.revanced:revanced-patcher:1.0.0")
|
implementation("app.revanced:revanced-patcher:1.1.0")
|
||||||
|
|
||||||
implementation("info.picocli:picocli:4.6.3")
|
implementation("info.picocli:picocli:4.6.3")
|
||||||
|
implementation("com.android.tools.build:apksig:7.2.1")
|
||||||
implementation("com.github.li-wjohnson:jadb:master-SNAPSHOT") // using a fork instead.
|
implementation("com.github.revanced:jadb:master-SNAPSHOT") // updated fork
|
||||||
implementation("org.bouncycastle:bcpkix-jdk15on:1.70")
|
implementation("org.bouncycastle:bcpkix-jdk15on:1.70")
|
||||||
implementation("org.jetbrains.kotlin:kotlin-reflect:1.6.21")
|
implementation("org.jetbrains.kotlin:kotlin-reflect:1.6.21")
|
||||||
}
|
}
|
||||||
@ -44,7 +45,7 @@ tasks {
|
|||||||
}
|
}
|
||||||
shadowJar {
|
shadowJar {
|
||||||
manifest {
|
manifest {
|
||||||
attributes("Main-Class" to "app.revanced.cli.MainKt")
|
attributes("Main-Class" to "app.revanced.cli.main.MainKt")
|
||||||
attributes("Implementation-Title" to project.name)
|
attributes("Implementation-Title" to project.name)
|
||||||
attributes("Implementation-Version" to project.version)
|
attributes("Implementation-Version" to project.version)
|
||||||
}
|
}
|
||||||
|
@ -1,96 +0,0 @@
|
|||||||
package app.revanced.cli
|
|
||||||
|
|
||||||
import app.revanced.patcher.PatcherOptions
|
|
||||||
import app.revanced.patcher.annotation.Name
|
|
||||||
import app.revanced.patcher.util.patch.implementation.JarPatchBundle
|
|
||||||
import app.revanced.utils.adb.Adb
|
|
||||||
import app.revanced.utils.patcher.addPatchesFiltered
|
|
||||||
import app.revanced.utils.signature.Signature
|
|
||||||
import picocli.CommandLine.*
|
|
||||||
import java.io.File
|
|
||||||
|
|
||||||
@Command(
|
|
||||||
name = "ReVanced-CLI", version = ["1.0.0"], mixinStandardHelpOptions = true
|
|
||||||
)
|
|
||||||
internal object MainCommand : Runnable {
|
|
||||||
@Parameters(
|
|
||||||
paramLabel = "INCLUDE",
|
|
||||||
description = ["Which patches to include. If none is specified, all compatible patches will be included"]
|
|
||||||
)
|
|
||||||
internal var includedPatches = arrayOf<String>()
|
|
||||||
|
|
||||||
@Option(names = ["-p", "--patches"], description = ["One or more bundles of patches"])
|
|
||||||
internal var patchBundles = arrayOf<String>()
|
|
||||||
|
|
||||||
@Option(names = ["-t", "--temp-dir"], description = ["Temporal resource cache directory"])
|
|
||||||
internal var cacheDirectory = "revanced-cache"
|
|
||||||
|
|
||||||
@Option(names = ["-r", "--resource-patcher"], description = ["Disable patching resources"])
|
|
||||||
internal var disableResourcePatching: Boolean = false
|
|
||||||
|
|
||||||
@Option(
|
|
||||||
names = ["-c", "--clean"],
|
|
||||||
description = ["Clean the temporal resource cache directory. This will be done anyways when running the patcher"]
|
|
||||||
)
|
|
||||||
internal var clean: Boolean = false
|
|
||||||
|
|
||||||
@Option(names = ["-l", "--list"], description = ["List patches only"])
|
|
||||||
internal var listOnly: Boolean = false
|
|
||||||
|
|
||||||
@Option(names = ["-s", "--signature-checker"], description = ["Check signatures of all patches"])
|
|
||||||
internal var signatureCheck: Boolean = false
|
|
||||||
|
|
||||||
@Option(names = ["-m", "--merge"], description = ["One or more dex file containers to merge"])
|
|
||||||
internal var mergeFiles = listOf<File>()
|
|
||||||
|
|
||||||
@Option(names = ["-a", "--apk"], description = ["Input file to be patched"], required = true)
|
|
||||||
internal lateinit var inputFile: File
|
|
||||||
|
|
||||||
@Option(names = ["-o", "--out"], description = ["Output file path"], required = true)
|
|
||||||
internal lateinit var outputPath: String
|
|
||||||
|
|
||||||
@Option(names = ["-d", "--deploy-on"], description = ["If specified, deploy to adb device with given name"])
|
|
||||||
internal var deploy: String? = null
|
|
||||||
|
|
||||||
@Option(names = ["-b", "--debugging"], description = ["Disable patch version compatibility"])
|
|
||||||
internal var debugging: Boolean = false
|
|
||||||
|
|
||||||
override fun run() {
|
|
||||||
if (listOnly) {
|
|
||||||
for (patchBundlePath in patchBundles) for (it in JarPatchBundle(patchBundlePath).loadPatches()) {
|
|
||||||
|
|
||||||
// TODO: adjust extension methods to be able to do this
|
|
||||||
val name = (it.annotations.find { it is Name } as? Name)?.name ?: it.simpleName
|
|
||||||
println(
|
|
||||||
"[available] $name"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
val patcher = app.revanced.patcher.Patcher(PatcherOptions(inputFile, cacheDirectory, !disableResourcePatching))
|
|
||||||
|
|
||||||
if (signatureCheck) {
|
|
||||||
patcher.addPatchesFiltered()
|
|
||||||
Signature.checkSignatures(patcher)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
val outputFile = File(outputPath)
|
|
||||||
|
|
||||||
var adb: Adb? = null
|
|
||||||
deploy?.let {
|
|
||||||
adb = Adb(
|
|
||||||
outputFile, patcher.packageName, deploy!!
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
Patcher.start(patcher)
|
|
||||||
|
|
||||||
if (clean) File(cacheDirectory).deleteRecursively()
|
|
||||||
|
|
||||||
adb?.deploy()
|
|
||||||
|
|
||||||
if (clean) outputFile.delete()
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,55 +0,0 @@
|
|||||||
package app.revanced.cli
|
|
||||||
|
|
||||||
import app.revanced.utils.filesystem.FileSystemUtils
|
|
||||||
import app.revanced.utils.patcher.addPatchesFiltered
|
|
||||||
import app.revanced.utils.patcher.applyPatchesPrint
|
|
||||||
import app.revanced.utils.patcher.mergeFiles
|
|
||||||
import app.revanced.utils.signing.Signer
|
|
||||||
import java.io.File
|
|
||||||
import java.io.FileFilter
|
|
||||||
|
|
||||||
internal class Patcher {
|
|
||||||
internal companion object {
|
|
||||||
internal fun start(patcher: app.revanced.patcher.Patcher) {
|
|
||||||
// merge files like necessary integrations
|
|
||||||
patcher.mergeFiles()
|
|
||||||
// add patches, but filter incompatible or excluded patches
|
|
||||||
patcher.addPatchesFiltered(includeFilter = MainCommand.includedPatches.isNotEmpty())
|
|
||||||
// apply patches
|
|
||||||
patcher.applyPatchesPrint()
|
|
||||||
|
|
||||||
// write output file
|
|
||||||
val outFile = File(MainCommand.outputPath)
|
|
||||||
if (outFile.exists()) outFile.delete()
|
|
||||||
MainCommand.inputFile.copyTo(outFile)
|
|
||||||
|
|
||||||
val zipFileSystem = FileSystemUtils(outFile)
|
|
||||||
|
|
||||||
// replace all dex files
|
|
||||||
for ((name, data) in patcher.save()) {
|
|
||||||
zipFileSystem.replaceFile(name, data.data)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!MainCommand.disableResourcePatching) {
|
|
||||||
for (file in File(MainCommand.cacheDirectory).resolve("build/").listFiles(FileFilter { it.isDirectory })
|
|
||||||
?.first()?.listFiles()!!) {
|
|
||||||
if (!file.isDirectory) {
|
|
||||||
zipFileSystem.replaceFile(file.name, file.readBytes())
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
zipFileSystem.replaceDirectory(file)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// finally close the stream
|
|
||||||
zipFileSystem.close()
|
|
||||||
|
|
||||||
// and sign the apk file
|
|
||||||
Signer.signApk(outFile)
|
|
||||||
|
|
||||||
println("[done]")
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
108
src/main/kotlin/app/revanced/cli/command/MainCommand.kt
Normal file
108
src/main/kotlin/app/revanced/cli/command/MainCommand.kt
Normal file
@ -0,0 +1,108 @@
|
|||||||
|
package app.revanced.cli.command
|
||||||
|
|
||||||
|
import app.revanced.cli.patcher.Patcher
|
||||||
|
import app.revanced.cli.signing.Signing
|
||||||
|
import app.revanced.patcher.PatcherOptions
|
||||||
|
import app.revanced.patcher.extensions.PatchExtensions.patchName
|
||||||
|
import app.revanced.patcher.util.patch.implementation.JarPatchBundle
|
||||||
|
import app.revanced.utils.adb.Adb
|
||||||
|
import picocli.CommandLine.Command
|
||||||
|
import picocli.CommandLine.Option
|
||||||
|
import java.io.File
|
||||||
|
import java.nio.file.Files
|
||||||
|
|
||||||
|
@Command(
|
||||||
|
name = "ReVanced-CLI", version = ["1.0.0"], mixinStandardHelpOptions = true,
|
||||||
|
)
|
||||||
|
internal object MainCommand : Runnable {
|
||||||
|
@Option(names = ["-a", "--apk"], description = ["Input file to be patched"], required = true)
|
||||||
|
lateinit var inputFile: File
|
||||||
|
|
||||||
|
@Option(names = ["-o", "--out"], description = ["Output file path"], required = true)
|
||||||
|
lateinit var outputPath: String
|
||||||
|
|
||||||
|
@Option(
|
||||||
|
names = ["-i", "--include"],
|
||||||
|
description = ["Which patches to include. If none is specified, all compatible default patches will be included"]
|
||||||
|
)
|
||||||
|
var includedPatches = arrayOf<String>()
|
||||||
|
|
||||||
|
@Option(names = ["-r", "--resource-patcher"], description = ["Disable patching resources"])
|
||||||
|
var disableResourcePatching: Boolean = false
|
||||||
|
|
||||||
|
@Option(names = ["--debugging"], description = ["Disable patch version compatibility"])
|
||||||
|
var debugging: Boolean = false
|
||||||
|
|
||||||
|
@Option(names = ["-m", "--merge"], description = ["One or more dex file containers to merge"])
|
||||||
|
var mergeFiles = listOf<File>()
|
||||||
|
|
||||||
|
@Option(names = ["-b", "--bundles"], description = ["One or more bundles of patches"])
|
||||||
|
var patchBundles = arrayOf<String>()
|
||||||
|
|
||||||
|
@Option(names = ["-l", "--list"], description = ["List patches only"])
|
||||||
|
var listOnly: Boolean = false
|
||||||
|
|
||||||
|
@Option(names = ["--install"], description = ["If specified, instead of mounting, install"])
|
||||||
|
var install: Boolean = false
|
||||||
|
|
||||||
|
@Option(names = ["--cn"], description = ["Overwrite the default CN for the signed file"])
|
||||||
|
var cn = "ReVanced"
|
||||||
|
|
||||||
|
@Option(names = ["-p", "--password"], description = ["Overwrite the default password for the signed file"])
|
||||||
|
var password = "ReVanced"
|
||||||
|
|
||||||
|
@Option(names = ["-d", "--deploy-on"], description = ["If specified, deploy to adb device with given name"])
|
||||||
|
var deploy: String? = null
|
||||||
|
|
||||||
|
@Option(names = ["-t", "--temp-dir"], description = ["Temporal resource cache directory"])
|
||||||
|
var cacheDirectory = "revanced-cache"
|
||||||
|
|
||||||
|
@Option(
|
||||||
|
names = ["-c", "--clean"],
|
||||||
|
description = ["Clean the temporal resource cache directory. This will be done anyways when running the patcher"]
|
||||||
|
)
|
||||||
|
var clean: Boolean = false
|
||||||
|
|
||||||
|
override fun run() {
|
||||||
|
if (listOnly) {
|
||||||
|
for (patchBundlePath in patchBundles) for (patch in JarPatchBundle(patchBundlePath).loadPatches()) {
|
||||||
|
println("[available] ${patch.patchName}")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
val patcher = app.revanced.patcher.Patcher(PatcherOptions(inputFile, cacheDirectory, !disableResourcePatching))
|
||||||
|
|
||||||
|
val outputFile = File(outputPath)
|
||||||
|
|
||||||
|
val adb: Adb? = deploy?.let {
|
||||||
|
Adb(outputFile, patcher.data.packageMetadata.packageName, deploy!!, install)
|
||||||
|
}
|
||||||
|
|
||||||
|
val patchedFile = if (install) File(cacheDirectory).resolve("${outputFile.nameWithoutExtension}_raw.apk") else outputFile
|
||||||
|
|
||||||
|
Patcher.start(patcher, patchedFile)
|
||||||
|
|
||||||
|
println("[aligning & signing]")
|
||||||
|
|
||||||
|
if (install) {
|
||||||
|
Signing.start(
|
||||||
|
patchedFile,
|
||||||
|
outputFile,
|
||||||
|
cn,
|
||||||
|
password,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (clean) File(cacheDirectory).deleteRecursively()
|
||||||
|
|
||||||
|
adb?.let {
|
||||||
|
println("[deploying]")
|
||||||
|
it.deploy()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (clean && deploy != null) Files.delete(outputFile.toPath())
|
||||||
|
|
||||||
|
println("[done]")
|
||||||
|
}
|
||||||
|
}
|
@ -1,5 +1,6 @@
|
|||||||
package app.revanced.cli
|
package app.revanced.cli.main
|
||||||
|
|
||||||
|
import app.revanced.cli.command.MainCommand
|
||||||
import picocli.CommandLine
|
import picocli.CommandLine
|
||||||
|
|
||||||
internal fun main(args: Array<String>) {
|
internal fun main(args: Array<String>) {
|
41
src/main/kotlin/app/revanced/cli/patcher/Patcher.kt
Normal file
41
src/main/kotlin/app/revanced/cli/patcher/Patcher.kt
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
package app.revanced.cli.patcher
|
||||||
|
|
||||||
|
import app.revanced.cli.command.MainCommand.cacheDirectory
|
||||||
|
import app.revanced.cli.command.MainCommand.disableResourcePatching
|
||||||
|
import app.revanced.cli.command.MainCommand
|
||||||
|
import app.revanced.cli.command.MainCommand.includedPatches
|
||||||
|
import app.revanced.utils.filesystem.ZipFileSystemUtils
|
||||||
|
import app.revanced.utils.patcher.addPatchesFiltered
|
||||||
|
import app.revanced.utils.patcher.applyPatchesVerbose
|
||||||
|
import app.revanced.utils.patcher.mergeFiles
|
||||||
|
import java.io.File
|
||||||
|
import java.nio.file.Files
|
||||||
|
|
||||||
|
internal object Patcher {
|
||||||
|
internal fun start(patcher: app.revanced.patcher.Patcher, output: File) {
|
||||||
|
// merge files like necessary integrations
|
||||||
|
patcher.mergeFiles()
|
||||||
|
// add patches, but filter incompatible or excluded patches
|
||||||
|
patcher.addPatchesFiltered(includeFilter = includedPatches.isNotEmpty())
|
||||||
|
// apply patches
|
||||||
|
patcher.applyPatchesVerbose()
|
||||||
|
|
||||||
|
// write output file
|
||||||
|
if (output.exists()) Files.delete(output.toPath())
|
||||||
|
MainCommand.inputFile.copyTo(output)
|
||||||
|
|
||||||
|
ZipFileSystemUtils(output).use { fileSystem ->
|
||||||
|
// replace all dex files
|
||||||
|
val result = patcher.save()
|
||||||
|
result.dexFiles.forEach {
|
||||||
|
fileSystem.write(it.name, it.memoryDataStore.data)
|
||||||
|
}
|
||||||
|
|
||||||
|
// write resources
|
||||||
|
if (!disableResourcePatching) {
|
||||||
|
fileSystem.writePathRecursively(File(cacheDirectory).resolve("build").toPath())
|
||||||
|
fileSystem.uncompress(*result.doNotCompress!!.toTypedArray())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
24
src/main/kotlin/app/revanced/cli/signing/Signing.kt
Normal file
24
src/main/kotlin/app/revanced/cli/signing/Signing.kt
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
package app.revanced.cli.signing
|
||||||
|
|
||||||
|
import app.revanced.cli.command.MainCommand.cacheDirectory
|
||||||
|
import app.revanced.utils.signing.Signer
|
||||||
|
import app.revanced.utils.signing.align.ZipAligner
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
object Signing {
|
||||||
|
fun start(inputFile: File, outputFile: File, cn: String, password: String) {
|
||||||
|
val cacheDirectory = File(cacheDirectory)
|
||||||
|
val alignedOutput = cacheDirectory.resolve("${outputFile.nameWithoutExtension}_aligned.apk")
|
||||||
|
val signedOutput = cacheDirectory.resolve("${outputFile.nameWithoutExtension}_signed.apk")
|
||||||
|
|
||||||
|
// align the inputFile and write to alignedOutput
|
||||||
|
ZipAligner.align(inputFile, alignedOutput)
|
||||||
|
// sign the alignedOutput and write to signedOutput
|
||||||
|
// the reason is, in case the signer fails
|
||||||
|
// it does not damage the output file
|
||||||
|
Signer(cn, password).signApk(alignedOutput, signedOutput)
|
||||||
|
|
||||||
|
// afterwards copy over the file to the output
|
||||||
|
signedOutput.copyTo(outputFile, true)
|
||||||
|
}
|
||||||
|
}
|
@ -2,13 +2,15 @@ package app.revanced.utils.adb
|
|||||||
|
|
||||||
import se.vidstige.jadb.JadbConnection
|
import se.vidstige.jadb.JadbConnection
|
||||||
import se.vidstige.jadb.JadbDevice
|
import se.vidstige.jadb.JadbDevice
|
||||||
|
import se.vidstige.jadb.managers.PackageManager
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.util.concurrent.Executors
|
import java.util.concurrent.Executors
|
||||||
|
|
||||||
internal class Adb(
|
internal class Adb(
|
||||||
private val apk: File,
|
private val file: File,
|
||||||
private val packageName: String,
|
private val packageName: String,
|
||||||
deviceName: String,
|
deviceName: String,
|
||||||
|
private val modeInstall: Boolean = false,
|
||||||
private val logging: Boolean = true
|
private val logging: Boolean = true
|
||||||
) {
|
) {
|
||||||
private val device: JadbDevice
|
private val device: JadbDevice
|
||||||
@ -17,49 +19,54 @@ internal class Adb(
|
|||||||
device = JadbConnection().devices.find { it.serial == deviceName }
|
device = JadbConnection().devices.find { it.serial == deviceName }
|
||||||
?: throw IllegalArgumentException("No such device with name $deviceName")
|
?: throw IllegalArgumentException("No such device with name $deviceName")
|
||||||
|
|
||||||
if (device.run("su -h", false) != 0)
|
if (!modeInstall && device.run("su -h", false) != 0)
|
||||||
throw IllegalArgumentException("Root required on $deviceName. Deploying failed.")
|
throw IllegalArgumentException("Root required on $deviceName. Deploying failed.")
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun String.replacePlaceholder(): String {
|
private fun String.replacePlaceholder(with: String? = null): String {
|
||||||
return this.replace(Constants.PLACEHOLDER, packageName)
|
return this.replace(Constants.PLACEHOLDER, with ?: packageName)
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun deploy() {
|
internal fun deploy() {
|
||||||
// create revanced path
|
if (modeInstall) {
|
||||||
device.run("${Constants.COMMAND_CREATE_DIR} ${Constants.PATH_REVANCED}")
|
PackageManager(device).install(file)
|
||||||
|
} else {
|
||||||
|
// push patched file
|
||||||
|
device.copy(Constants.PATH_INIT_PUSH, file)
|
||||||
|
|
||||||
// push patched file
|
// create revanced path
|
||||||
device.copy(Constants.PATH_INIT_PUSH, apk)
|
device.run("${Constants.COMMAND_CREATE_DIR} ${Constants.PATH_REVANCED}")
|
||||||
// install apk
|
|
||||||
device.run(Constants.COMMAND_INSTALL_APK.replacePlaceholder())
|
|
||||||
|
|
||||||
// push mount script
|
// prepare mounting the apk
|
||||||
device.createFile(
|
device.run(Constants.COMMAND_PREPARE_MOUNT_APK.replacePlaceholder())
|
||||||
Constants.PATH_INIT_PUSH,
|
|
||||||
Constants.CONTENT_MOUNT_SCRIPT.replacePlaceholder()
|
|
||||||
)
|
|
||||||
// install mount script
|
|
||||||
device.run(Constants.COMMAND_INSTALL_MOUNT.replacePlaceholder())
|
|
||||||
|
|
||||||
// push umount script
|
// push mount script
|
||||||
device.createFile(
|
device.createFile(
|
||||||
Constants.PATH_INIT_PUSH,
|
Constants.PATH_INIT_PUSH,
|
||||||
Constants.CONTENT_UMOUNT_SCRIPT.replacePlaceholder()
|
Constants.CONTENT_MOUNT_SCRIPT.replacePlaceholder()
|
||||||
)
|
)
|
||||||
// install mount script
|
// install mount script
|
||||||
device.run(Constants.COMMAND_INSTALL_UMOUNT.replacePlaceholder())
|
device.run(Constants.COMMAND_INSTALL_MOUNT.replacePlaceholder())
|
||||||
|
|
||||||
// unmount the apk for sanity
|
// push umount script
|
||||||
device.run(Constants.PATH_UMOUNT.replacePlaceholder())
|
device.createFile(
|
||||||
// mount the apk
|
Constants.PATH_INIT_PUSH,
|
||||||
device.run(Constants.PATH_MOUNT.replacePlaceholder())
|
Constants.CONTENT_UMOUNT_SCRIPT.replacePlaceholder()
|
||||||
|
)
|
||||||
|
// install mount script
|
||||||
|
device.run(Constants.COMMAND_INSTALL_UMOUNT.replacePlaceholder())
|
||||||
|
|
||||||
// relaunch app
|
// unmount the apk for sanity
|
||||||
device.run(Constants.COMMAND_RESTART.replacePlaceholder())
|
device.run(Constants.PATH_UMOUNT.replacePlaceholder())
|
||||||
|
// mount the apk
|
||||||
|
device.run(Constants.PATH_MOUNT.replacePlaceholder())
|
||||||
|
|
||||||
// log the app
|
// relaunch app
|
||||||
log()
|
device.run(Constants.COMMAND_RESTART.replacePlaceholder())
|
||||||
|
|
||||||
|
// log the app
|
||||||
|
log()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun log() {
|
private fun log() {
|
||||||
|
@ -15,7 +15,7 @@ internal object Constants {
|
|||||||
private const val NAME_MOUNT_SCRIPT = "mount_revanced_$PLACEHOLDER.sh"
|
private const val NAME_MOUNT_SCRIPT = "mount_revanced_$PLACEHOLDER.sh"
|
||||||
|
|
||||||
// initial directory to push files to via adb push
|
// initial directory to push files to via adb push
|
||||||
internal const val PATH_INIT_PUSH = "/sdcard/revanced.delete"
|
internal const val PATH_INIT_PUSH = "/data/local/tmp/revanced.delete"
|
||||||
|
|
||||||
// revanced path
|
// revanced path
|
||||||
internal const val PATH_REVANCED = "/data/adb/revanced/"
|
internal const val PATH_REVANCED = "/data/adb/revanced/"
|
||||||
@ -28,7 +28,7 @@ internal object Constants {
|
|||||||
internal const val PATH_UMOUNT = "/data/adb/post-fs-data.d/un$NAME_MOUNT_SCRIPT"
|
internal const val PATH_UMOUNT = "/data/adb/post-fs-data.d/un$NAME_MOUNT_SCRIPT"
|
||||||
|
|
||||||
// move to revanced apk path & set permissions
|
// move to revanced apk path & set permissions
|
||||||
internal const val COMMAND_INSTALL_APK =
|
internal const val COMMAND_PREPARE_MOUNT_APK =
|
||||||
"base_path=\"$PATH_REVANCED_APP\" && mv $PATH_INIT_PUSH ${'$'}base_path && chmod 644 ${'$'}base_path && chown system:system ${'$'}base_path && chcon u:object_r:apk_data_file:s0 ${'$'}base_path"
|
"base_path=\"$PATH_REVANCED_APP\" && mv $PATH_INIT_PUSH ${'$'}base_path && chmod 644 ${'$'}base_path && chown system:system ${'$'}base_path && chcon u:object_r:apk_data_file:s0 ${'$'}base_path"
|
||||||
|
|
||||||
// install mount script & set permissions
|
// install mount script & set permissions
|
||||||
|
@ -1,63 +0,0 @@
|
|||||||
package app.revanced.utils.filesystem
|
|
||||||
|
|
||||||
import java.io.Closeable
|
|
||||||
import java.io.File
|
|
||||||
import java.nio.file.FileSystem
|
|
||||||
import java.nio.file.FileSystems
|
|
||||||
import java.nio.file.Files
|
|
||||||
|
|
||||||
internal class FileSystemUtils(
|
|
||||||
file: File
|
|
||||||
) : Closeable {
|
|
||||||
private var fileSystem: FileSystem
|
|
||||||
|
|
||||||
init {
|
|
||||||
fileSystem = FileSystems.newFileSystem(file.toPath(), null as ClassLoader?)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun deleteDirectory(dirPath: String) {
|
|
||||||
val files = Files.walk(fileSystem.getPath("$dirPath/"))
|
|
||||||
|
|
||||||
files
|
|
||||||
.sorted(Comparator.reverseOrder())
|
|
||||||
.forEach {
|
|
||||||
|
|
||||||
Files.delete(it)
|
|
||||||
}
|
|
||||||
|
|
||||||
files.close()
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
internal fun replaceDirectory(replacement: File) {
|
|
||||||
if (!replacement.isDirectory) throw Exception("${replacement.name} is not a directory.")
|
|
||||||
|
|
||||||
// FIXME: make this delete the directory recursively
|
|
||||||
//deleteDirectory(replacement.name)
|
|
||||||
//val path = Files.createDirectory(fileSystem.getPath(replacement.name))
|
|
||||||
|
|
||||||
val excludeFromPath = replacement.path.removeSuffix(replacement.name)
|
|
||||||
for (path in Files.walk(replacement.toPath())) {
|
|
||||||
val file = path.toFile()
|
|
||||||
if (file.isDirectory) {
|
|
||||||
val relativePath = path.toString().removePrefix(excludeFromPath)
|
|
||||||
val fileSystemPath = fileSystem.getPath(relativePath)
|
|
||||||
if (!Files.exists(fileSystemPath)) Files.createDirectory(fileSystemPath)
|
|
||||||
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
replaceFile(path.toString().removePrefix(excludeFromPath), file.readBytes())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
internal fun replaceFile(sourceFile: String, content: ByteArray) {
|
|
||||||
val path = fileSystem.getPath(sourceFile)
|
|
||||||
Files.deleteIfExists(path)
|
|
||||||
Files.write(path, content)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun close() {
|
|
||||||
fileSystem.close()
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,59 @@
|
|||||||
|
package app.revanced.utils.filesystem
|
||||||
|
|
||||||
|
import java.io.Closeable
|
||||||
|
import java.io.File
|
||||||
|
import java.nio.file.FileSystems
|
||||||
|
import java.nio.file.Files
|
||||||
|
import java.nio.file.Path
|
||||||
|
import java.util.zip.ZipEntry
|
||||||
|
|
||||||
|
internal class ZipFileSystemUtils(
|
||||||
|
file: File
|
||||||
|
) : Closeable {
|
||||||
|
private var zipFileSystem = FileSystems.newFileSystem(file.toPath(), mapOf("noCompression" to true))
|
||||||
|
|
||||||
|
private fun Path.deleteRecursively() {
|
||||||
|
if (Files.isDirectory(this)) {
|
||||||
|
Files.list(this).forEach { path ->
|
||||||
|
path.deleteRecursively()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Files.delete(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun writePathRecursively(path: Path) {
|
||||||
|
Files.list(path).let { fileStream ->
|
||||||
|
fileStream.forEach { filePath ->
|
||||||
|
val fileSystemPath = filePath.getRelativePath(path)
|
||||||
|
fileSystemPath.deleteRecursively()
|
||||||
|
}
|
||||||
|
|
||||||
|
fileStream
|
||||||
|
}.close()
|
||||||
|
|
||||||
|
Files.walk(path).let { fileStream ->
|
||||||
|
fileStream.skip(1).forEach { filePath ->
|
||||||
|
val relativePath = filePath.getRelativePath(path)
|
||||||
|
|
||||||
|
if (Files.isDirectory(filePath)) {
|
||||||
|
Files.createDirectory(relativePath)
|
||||||
|
return@forEach
|
||||||
|
}
|
||||||
|
|
||||||
|
Files.copy(filePath, relativePath)
|
||||||
|
}
|
||||||
|
|
||||||
|
fileStream
|
||||||
|
}.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun write(path: String, content: ByteArray) = Files.write(zipFileSystem.getPath(path), content)
|
||||||
|
|
||||||
|
private fun Path.getRelativePath(path: Path): Path = zipFileSystem.getPath(path.relativize(this).toString())
|
||||||
|
|
||||||
|
internal fun uncompress(vararg paths: String) =
|
||||||
|
paths.forEach { Files.setAttribute(zipFileSystem.getPath(it), "zip:method", ZipEntry.STORED) }
|
||||||
|
|
||||||
|
override fun close() = zipFileSystem.close()
|
||||||
|
}
|
@ -1,9 +1,12 @@
|
|||||||
package app.revanced.utils.patcher
|
package app.revanced.utils.patcher
|
||||||
|
|
||||||
import app.revanced.cli.MainCommand
|
import app.revanced.cli.command.MainCommand
|
||||||
|
import app.revanced.cli.command.MainCommand.debugging
|
||||||
|
import app.revanced.cli.command.MainCommand.patchBundles
|
||||||
import app.revanced.patcher.Patcher
|
import app.revanced.patcher.Patcher
|
||||||
import app.revanced.patcher.data.base.Data
|
import app.revanced.patcher.data.base.Data
|
||||||
import app.revanced.patcher.extensions.PatchExtensions.compatiblePackages
|
import app.revanced.patcher.extensions.PatchExtensions.compatiblePackages
|
||||||
|
import app.revanced.patcher.extensions.PatchExtensions.include
|
||||||
import app.revanced.patcher.extensions.PatchExtensions.patchName
|
import app.revanced.patcher.extensions.PatchExtensions.patchName
|
||||||
import app.revanced.patcher.patch.base.Patch
|
import app.revanced.patcher.patch.base.Patch
|
||||||
import app.revanced.patcher.util.patch.implementation.JarPatchBundle
|
import app.revanced.patcher.util.patch.implementation.JarPatchBundle
|
||||||
@ -11,10 +14,10 @@ import app.revanced.patcher.util.patch.implementation.JarPatchBundle
|
|||||||
fun Patcher.addPatchesFiltered(
|
fun Patcher.addPatchesFiltered(
|
||||||
includeFilter: Boolean = false
|
includeFilter: Boolean = false
|
||||||
) {
|
) {
|
||||||
val packageName = this.packageName
|
val packageName = this.data.packageMetadata.packageName
|
||||||
val packageVersion = this.packageVersion
|
val packageVersion = this.data.packageMetadata.packageVersion
|
||||||
|
|
||||||
MainCommand.patchBundles.forEach { bundle ->
|
patchBundles.forEach { bundle ->
|
||||||
val includedPatches = mutableListOf<Class<out Patch<Data>>>()
|
val includedPatches = mutableListOf<Class<out Patch<Data>>>()
|
||||||
JarPatchBundle(bundle).loadPatches().forEach patch@{ patch ->
|
JarPatchBundle(bundle).loadPatches().forEach patch@{ patch ->
|
||||||
val compatiblePackages = patch.compatiblePackages
|
val compatiblePackages = patch.compatiblePackages
|
||||||
@ -22,8 +25,13 @@ fun Patcher.addPatchesFiltered(
|
|||||||
|
|
||||||
val prefix = "[skipped] $patchName"
|
val prefix = "[skipped] $patchName"
|
||||||
|
|
||||||
if (includeFilter && !MainCommand.includedPatches.contains(patchName)) {
|
if (includeFilter) {
|
||||||
println(prefix)
|
if (!MainCommand.includedPatches.contains(patchName)) {
|
||||||
|
println("$prefix: Explicitly excluded.")
|
||||||
|
return@patch
|
||||||
|
}
|
||||||
|
} else if (!patch.include) {
|
||||||
|
println("$prefix: Implicitly excluded.")
|
||||||
return@patch
|
return@patch
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -34,7 +42,7 @@ fun Patcher.addPatchesFiltered(
|
|||||||
return@patch
|
return@patch
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!(MainCommand.debugging || compatiblePackage.versions.any { it == packageVersion })) {
|
if (!(debugging || compatiblePackage.versions.any { it == packageVersion })) {
|
||||||
println("$prefix: Unsupported version.")
|
println("$prefix: Unsupported version.")
|
||||||
return@patch
|
return@patch
|
||||||
}
|
}
|
||||||
@ -47,7 +55,7 @@ fun Patcher.addPatchesFiltered(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun Patcher.applyPatchesPrint() {
|
fun Patcher.applyPatchesVerbose() {
|
||||||
this.applyPatches().forEach { (patch, result) ->
|
this.applyPatches().forEach { (patch, result) ->
|
||||||
if (result.isSuccess) {
|
if (result.isSuccess) {
|
||||||
println("[success] $patch")
|
println("[success] $patch")
|
||||||
|
@ -1,9 +0,0 @@
|
|||||||
package app.revanced.utils.signing
|
|
||||||
|
|
||||||
import java.security.PrivateKey
|
|
||||||
import java.security.cert.X509Certificate
|
|
||||||
|
|
||||||
data class KeySet(
|
|
||||||
val publicKey: X509Certificate,
|
|
||||||
val privateKey: PrivateKey
|
|
||||||
)
|
|
@ -1,65 +1,40 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) 2021 Juby210 & Vendicated
|
|
||||||
* Licensed under the Open Software License version 3.0
|
|
||||||
*/
|
|
||||||
|
|
||||||
package app.revanced.utils.signing
|
package app.revanced.utils.signing
|
||||||
|
|
||||||
|
import com.android.apksig.ApkSigner
|
||||||
import org.bouncycastle.asn1.x500.X500Name
|
import org.bouncycastle.asn1.x500.X500Name
|
||||||
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo
|
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo
|
||||||
import org.bouncycastle.cert.X509v3CertificateBuilder
|
import org.bouncycastle.cert.X509v3CertificateBuilder
|
||||||
import org.bouncycastle.cert.jcajce.JcaCertStore
|
|
||||||
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter
|
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter
|
||||||
import org.bouncycastle.cms.*
|
|
||||||
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder
|
|
||||||
import org.bouncycastle.jce.provider.BouncyCastleProvider
|
import org.bouncycastle.jce.provider.BouncyCastleProvider
|
||||||
import org.bouncycastle.operator.ContentSigner
|
import org.bouncycastle.operator.ContentSigner
|
||||||
import org.bouncycastle.operator.DigestCalculatorProvider
|
|
||||||
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder
|
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder
|
||||||
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder
|
|
||||||
import org.bouncycastle.util.encoders.Base64
|
|
||||||
import java.io.ByteArrayOutputStream
|
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.FileInputStream
|
import java.io.FileInputStream
|
||||||
import java.io.FileOutputStream
|
import java.io.FileOutputStream
|
||||||
import java.math.BigInteger
|
import java.math.BigInteger
|
||||||
import java.nio.file.FileSystems
|
|
||||||
import java.nio.file.Files
|
|
||||||
import java.nio.file.Path
|
|
||||||
import java.security.*
|
import java.security.*
|
||||||
import java.security.cert.X509Certificate
|
import java.security.cert.X509Certificate
|
||||||
import java.util.*
|
import java.util.*
|
||||||
import java.util.jar.Attributes
|
|
||||||
import java.util.jar.JarFile
|
|
||||||
import java.util.jar.Manifest
|
|
||||||
import java.util.regex.Pattern
|
|
||||||
|
|
||||||
|
internal class Signer(
|
||||||
const val CN = "ReVanced"
|
private val cn: String, password: String
|
||||||
val PASSWORD = "revanced".toCharArray() // TODO: make it secure; random password should be enough
|
) {
|
||||||
|
private val passwordCharArray = password.toCharArray()
|
||||||
/**
|
|
||||||
* APK Signer.
|
|
||||||
* @author Aliucord authors
|
|
||||||
* @author ReVanced team
|
|
||||||
*/
|
|
||||||
object Signer {
|
|
||||||
private fun newKeystore(out: File) {
|
private fun newKeystore(out: File) {
|
||||||
val key = createKey()
|
val (publicKey, privateKey) = createKey()
|
||||||
val privateKS = KeyStore.getInstance("BKS", "BC")
|
val privateKS = KeyStore.getInstance("BKS", "BC")
|
||||||
privateKS.load(null, PASSWORD)
|
privateKS.load(null, passwordCharArray)
|
||||||
privateKS.setKeyEntry("alias", key.privateKey, PASSWORD, arrayOf(key.publicKey))
|
privateKS.setKeyEntry("alias", privateKey, passwordCharArray, arrayOf(publicKey))
|
||||||
privateKS.store(FileOutputStream(out), PASSWORD)
|
privateKS.store(FileOutputStream(out), passwordCharArray)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun createKey(): KeySet {
|
private fun createKey(): Pair<X509Certificate, PrivateKey> {
|
||||||
val gen = KeyPairGenerator.getInstance("RSA")
|
val gen = KeyPairGenerator.getInstance("RSA")
|
||||||
gen.initialize(2048)
|
gen.initialize(2048)
|
||||||
val pair = gen.generateKeyPair()
|
val pair = gen.generateKeyPair()
|
||||||
var serialNumber: BigInteger
|
var serialNumber: BigInteger
|
||||||
do serialNumber =
|
do serialNumber = BigInteger.valueOf(SecureRandom().nextLong()) while (serialNumber < BigInteger.ZERO)
|
||||||
BigInteger.valueOf(SecureRandom().nextLong()) while (serialNumber < BigInteger.ZERO)
|
val x500Name = X500Name("CN=$cn")
|
||||||
val x500Name = X500Name("CN=$CN")
|
|
||||||
val builder = X509v3CertificateBuilder(
|
val builder = X509v3CertificateBuilder(
|
||||||
x500Name,
|
x500Name,
|
||||||
serialNumber,
|
serialNumber,
|
||||||
@ -69,143 +44,31 @@ object Signer {
|
|||||||
x500Name,
|
x500Name,
|
||||||
SubjectPublicKeyInfo.getInstance(pair.public.encoded)
|
SubjectPublicKeyInfo.getInstance(pair.public.encoded)
|
||||||
)
|
)
|
||||||
val signer: ContentSigner = JcaContentSignerBuilder("SHA1withRSA").build(pair.private)
|
val signer: ContentSigner = JcaContentSignerBuilder("SHA256withRSA").build(pair.private)
|
||||||
return KeySet(JcaX509CertificateConverter().getCertificate(builder.build(signer)), pair.private)
|
return JcaX509CertificateConverter().getCertificate(builder.build(signer)) to pair.private
|
||||||
}
|
}
|
||||||
|
|
||||||
private val stripPattern: Pattern = Pattern.compile("^META-INF/(.*)[.](MF|SF|RSA|DSA)$")
|
fun signApk(input: File, output: File) {
|
||||||
|
|
||||||
// based on https://gist.github.com/mmuszkow/10288441
|
|
||||||
// and https://github.com/fornwall/apksigner/blob/master/src/main/java/net/fornwall/apksigner/ZipSigner.java
|
|
||||||
fun signApk(apkFile: File) {
|
|
||||||
Security.addProvider(BouncyCastleProvider())
|
Security.addProvider(BouncyCastleProvider())
|
||||||
|
|
||||||
val ks = File(apkFile.parent, "revanced-cli.keystore")
|
val ks = File(input.parent, "revanced-cli.keystore")
|
||||||
if (!ks.exists()) newKeystore(ks)
|
if (!ks.exists()) newKeystore(ks)
|
||||||
|
|
||||||
val keyStore = KeyStore.getInstance("BKS", "BC")
|
val keyStore = KeyStore.getInstance("BKS", "BC")
|
||||||
FileInputStream(ks).use { fis -> keyStore.load(fis, null) }
|
FileInputStream(ks).use { fis -> keyStore.load(fis, null) }
|
||||||
val alias = keyStore.aliases().nextElement()
|
val alias = keyStore.aliases().nextElement()
|
||||||
val keySet = KeySet(
|
|
||||||
(keyStore.getCertificate(alias) as X509Certificate),
|
|
||||||
(keyStore.getKey(alias, PASSWORD) as PrivateKey)
|
|
||||||
)
|
|
||||||
|
|
||||||
val zip = FileSystems.newFileSystem(apkFile.toPath(), null as ClassLoader?)
|
val config = ApkSigner.SignerConfig.Builder(
|
||||||
|
cn,
|
||||||
|
keyStore.getKey(alias, passwordCharArray) as PrivateKey,
|
||||||
|
listOf(keyStore.getCertificate(alias) as X509Certificate)
|
||||||
|
).build()
|
||||||
|
|
||||||
val dig = MessageDigest.getInstance("SHA1")
|
val signer = ApkSigner.Builder(listOf(config))
|
||||||
val digests: MutableMap<String, String> = LinkedHashMap()
|
signer.setCreatedBy(cn)
|
||||||
|
signer.setInputApk(input)
|
||||||
|
signer.setOutputApk(output)
|
||||||
|
|
||||||
for (entry in zip.allEntries) {
|
signer.build().sign()
|
||||||
val name = entry.toString()
|
|
||||||
if (stripPattern.matcher(name).matches()) {
|
|
||||||
Files.delete(entry)
|
|
||||||
} else {
|
|
||||||
digests[name] = toBase64(dig.digest(Files.readAllBytes(entry)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val sectionDigests: MutableMap<String, String> = LinkedHashMap()
|
|
||||||
var manifest = Manifest()
|
|
||||||
var attrs = manifest.mainAttributes
|
|
||||||
attrs[Attributes.Name.MANIFEST_VERSION] = "1.0"
|
|
||||||
attrs[Attributes.Name("Created-By")] = CN
|
|
||||||
|
|
||||||
val digestAttr = Attributes.Name("SHA1-Digest")
|
|
||||||
for ((name, value) in digests) {
|
|
||||||
val attributes = Attributes()
|
|
||||||
attributes[digestAttr] = value
|
|
||||||
manifest.entries[name] = attributes
|
|
||||||
sectionDigests[name] = hashEntrySection(name, attributes, dig)
|
|
||||||
}
|
|
||||||
ByteArrayOutputStream().use { baos ->
|
|
||||||
manifest.write(baos)
|
|
||||||
zip.writeFile(JarFile.MANIFEST_NAME, baos.toByteArray())
|
|
||||||
}
|
|
||||||
|
|
||||||
val manifestHash = getManifestHash(manifest, dig)
|
|
||||||
val tmpManifest = Manifest()
|
|
||||||
tmpManifest.mainAttributes.putAll(attrs)
|
|
||||||
val manifestMainHash = getManifestHash(tmpManifest, dig)
|
|
||||||
|
|
||||||
manifest = Manifest()
|
|
||||||
attrs = manifest.mainAttributes
|
|
||||||
attrs[Attributes.Name.SIGNATURE_VERSION] = "1.0"
|
|
||||||
attrs[Attributes.Name("Created-By")] = CN
|
|
||||||
attrs[Attributes.Name("SHA1-Digest-Manifest")] = manifestHash
|
|
||||||
attrs[Attributes.Name("SHA1-Digest-Manifest-Main-Attributes")] = manifestMainHash
|
|
||||||
|
|
||||||
for ((key, value) in sectionDigests) {
|
|
||||||
val attributes = Attributes()
|
|
||||||
attributes[digestAttr] = value
|
|
||||||
manifest.entries[key] = attributes
|
|
||||||
}
|
|
||||||
var sigBytes: ByteArray
|
|
||||||
ByteArrayOutputStream().use { sigStream ->
|
|
||||||
manifest.write(sigStream)
|
|
||||||
sigBytes = sigStream.toByteArray()
|
|
||||||
zip.writeFile("META-INF/CERT.SF", sigBytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
val signature = signSigFile(keySet, sigBytes)
|
|
||||||
zip.writeFile("META-INF/CERT.RSA", signature)
|
|
||||||
|
|
||||||
zip.close()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun hashEntrySection(name: String, attrs: Attributes, dig: MessageDigest): String {
|
|
||||||
val manifest = Manifest()
|
|
||||||
manifest.mainAttributes[Attributes.Name.MANIFEST_VERSION] = "1.0"
|
|
||||||
ByteArrayOutputStream().use { baos ->
|
|
||||||
manifest.write(baos)
|
|
||||||
val emptyLen = baos.toByteArray().size
|
|
||||||
manifest.entries[name] = attrs
|
|
||||||
baos.reset()
|
|
||||||
manifest.write(baos)
|
|
||||||
var ob = baos.toByteArray()
|
|
||||||
ob = Arrays.copyOfRange(ob, emptyLen, ob.size)
|
|
||||||
return toBase64(dig.digest(ob))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun getManifestHash(manifest: Manifest, dig: MessageDigest): String {
|
|
||||||
ByteArrayOutputStream().use { baos ->
|
|
||||||
manifest.write(baos)
|
|
||||||
return toBase64(dig.digest(baos.toByteArray()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun signSigFile(keySet: KeySet, content: ByteArray): ByteArray {
|
|
||||||
val msg: CMSTypedData = CMSProcessableByteArray(content)
|
|
||||||
val certs = JcaCertStore(Collections.singletonList(keySet.publicKey))
|
|
||||||
val gen = CMSSignedDataGenerator()
|
|
||||||
val jcaContentSignerBuilder = JcaContentSignerBuilder("SHA1withRSA")
|
|
||||||
val sha1Signer: ContentSigner = jcaContentSignerBuilder.build(keySet.privateKey)
|
|
||||||
val jcaDigestCalculatorProviderBuilder = JcaDigestCalculatorProviderBuilder()
|
|
||||||
val digestCalculatorProvider: DigestCalculatorProvider = jcaDigestCalculatorProviderBuilder.build()
|
|
||||||
val jcaSignerInfoGeneratorBuilder = JcaSignerInfoGeneratorBuilder(digestCalculatorProvider)
|
|
||||||
jcaSignerInfoGeneratorBuilder.setDirectSignature(true)
|
|
||||||
val signerInfoGenerator: SignerInfoGenerator = jcaSignerInfoGeneratorBuilder.build(sha1Signer, keySet.publicKey)
|
|
||||||
gen.addSignerInfoGenerator(signerInfoGenerator)
|
|
||||||
gen.addCertificates(certs)
|
|
||||||
val sigData: CMSSignedData = gen.generate(msg, false)
|
|
||||||
return sigData.toASN1Structure().getEncoded("DER")
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun toBase64(data: ByteArray): String {
|
|
||||||
return String(Base64.encode(data))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private val java.nio.file.FileSystem.allEntries: List<Path>
|
|
||||||
get() = buildList {
|
|
||||||
this@allEntries.rootDirectories.forEach { dir ->
|
|
||||||
Files.walk(dir).filter(Files::isRegularFile).forEach { file ->
|
|
||||||
this@buildList.add(file)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun java.nio.file.FileSystem.writeFile(path: String, bytes: ByteArray) {
|
|
||||||
Files.write(this.getPath("/$path"), bytes)
|
|
||||||
}
|
}
|
@ -0,0 +1,63 @@
|
|||||||
|
package app.revanced.utils.signing.align
|
||||||
|
|
||||||
|
import app.revanced.utils.signing.align.stream.MultiOutputStream
|
||||||
|
import app.revanced.utils.signing.align.stream.PeekingFakeStream
|
||||||
|
import java.io.BufferedOutputStream
|
||||||
|
import java.io.File
|
||||||
|
import java.util.*
|
||||||
|
import java.util.zip.ZipEntry
|
||||||
|
import java.util.zip.ZipFile
|
||||||
|
import java.util.zip.ZipOutputStream
|
||||||
|
|
||||||
|
internal object ZipAligner {
|
||||||
|
fun align(input: File, output: File, alignment: Int = 4) {
|
||||||
|
val zipFile = ZipFile(input)
|
||||||
|
|
||||||
|
val entries: Enumeration<out ZipEntry?> = zipFile.entries()
|
||||||
|
|
||||||
|
// fake
|
||||||
|
val peekingFakeStream = PeekingFakeStream()
|
||||||
|
val fakeOutputStream = ZipOutputStream(peekingFakeStream)
|
||||||
|
// real
|
||||||
|
val zipOutputStream = ZipOutputStream(BufferedOutputStream(output.outputStream()))
|
||||||
|
|
||||||
|
val multiOutputStream = MultiOutputStream(
|
||||||
|
listOf(
|
||||||
|
fakeOutputStream, // fake, used to add the data to the fake stream
|
||||||
|
zipOutputStream // real
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
var bias = 0
|
||||||
|
while (entries.hasMoreElements()) {
|
||||||
|
var padding = 0
|
||||||
|
|
||||||
|
val entry: ZipEntry = entries.nextElement()!!
|
||||||
|
// fake, used to calculate the file offset of the entry
|
||||||
|
fakeOutputStream.putNextEntry(entry)
|
||||||
|
|
||||||
|
if (entry.size == entry.compressedSize) {
|
||||||
|
val fileOffset = peekingFakeStream.peek()
|
||||||
|
val newOffset = fileOffset + bias
|
||||||
|
padding = ((alignment - (newOffset % alignment)) % alignment).toInt()
|
||||||
|
|
||||||
|
// real
|
||||||
|
entry.extra = if (entry.extra == null) ByteArray(padding)
|
||||||
|
else Arrays.copyOf(entry.extra, entry.extra.size + padding)
|
||||||
|
}
|
||||||
|
|
||||||
|
zipOutputStream.putNextEntry(entry)
|
||||||
|
zipFile.getInputStream(entry).copyTo(multiOutputStream)
|
||||||
|
|
||||||
|
// fake, used to add remaining bytes
|
||||||
|
fakeOutputStream.closeEntry()
|
||||||
|
// real
|
||||||
|
zipOutputStream.closeEntry()
|
||||||
|
|
||||||
|
bias += padding
|
||||||
|
}
|
||||||
|
|
||||||
|
zipFile.close()
|
||||||
|
zipOutputStream.close()
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,20 @@
|
|||||||
|
package app.revanced.utils.signing.align.stream
|
||||||
|
|
||||||
|
import java.io.OutputStream
|
||||||
|
|
||||||
|
internal class MultiOutputStream(
|
||||||
|
private val streams: Iterable<OutputStream>,
|
||||||
|
) : OutputStream() {
|
||||||
|
override fun write(b: ByteArray, off: Int, len: Int) = streams.forEach {
|
||||||
|
it.write(b, off, len)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun write(b: ByteArray) = streams.forEach {
|
||||||
|
it.write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun write(b: Int) = streams.forEach {
|
||||||
|
it.write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
package app.revanced.utils.signing.align.stream
|
||||||
|
|
||||||
|
import java.io.OutputStream
|
||||||
|
|
||||||
|
internal class PeekingFakeStream : OutputStream() {
|
||||||
|
private var numberOfBytes: Long = 0
|
||||||
|
|
||||||
|
fun peek() = numberOfBytes
|
||||||
|
|
||||||
|
override fun write(b: Int) {
|
||||||
|
numberOfBytes++
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun write(b: ByteArray) {
|
||||||
|
numberOfBytes += b.size
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun write(b: ByteArray, offset: Int, len: Int) {
|
||||||
|
numberOfBytes += len
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user