Frida.kt 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package com.example.modifier
  2. import android.util.Log
  3. import androidx.core.content.ContextCompat
  4. import kotlinx.coroutines.Dispatchers
  5. import kotlinx.coroutines.coroutineScope
  6. import kotlinx.coroutines.launch
  7. import kotlinx.coroutines.withContext
  8. import org.apache.commons.io.FileUtils
  9. import org.apache.commons.io.IOUtils
  10. import java.io.File
  11. import java.io.InterruptedIOException
  12. class Frida {
  13. companion object {
  14. var p: Process? = null
  15. var script: File? = null
  16. private val TAG = "FridaScript"
  17. suspend fun start() {
  18. if (p != null) {
  19. p!!.destroy()
  20. p = null
  21. }
  22. if (script != null) {
  23. script!!.delete()
  24. script = null
  25. }
  26. val context = Utils.getContext()
  27. val dataDir = ContextCompat.getDataDir(context)
  28. Utils.copyAssetFolder(context.assets, "bin", File(dataDir, "bin").path)
  29. val binPath = File(dataDir, "bin/frida-inject-16.3.3-android-arm64").path
  30. val pid = Utils.runAsRoot("pidof com.android.phone").trim()
  31. if (!Regex("[0-9]+").matches(pid)) {
  32. return
  33. }
  34. val scriptContent = IOUtils.toString(context.assets.open("scripts/phone.js"), "UTF-8")
  35. withContext(Dispatchers.IO) {
  36. script = File.createTempFile("script", ".js")
  37. FileUtils.writeStringToFile(script, scriptContent, "UTF-8")
  38. Log.i(TAG, "start: $binPath -p $pid -s $script")
  39. p = Runtime.getRuntime().exec("su -M")
  40. p!!.outputStream.bufferedWriter().use {
  41. it.write("chmod +x $binPath")
  42. it.newLine()
  43. it.flush()
  44. it.write("$binPath -p $pid -s $script")
  45. it.newLine()
  46. it.flush()
  47. }
  48. coroutineScope {
  49. launch {
  50. try {
  51. p!!.inputStream
  52. .bufferedReader()
  53. .useLines { lines ->
  54. lines.forEach {
  55. Log.i(TAG, it)
  56. }
  57. }
  58. } catch (e: Exception) {
  59. e.printStackTrace()
  60. }
  61. }
  62. launch {
  63. try {
  64. p!!.errorStream
  65. .bufferedReader()
  66. .useLines { lines ->
  67. lines.forEach {
  68. Log.e(TAG, it)
  69. }
  70. }
  71. } catch (e: Exception) {
  72. e.printStackTrace()
  73. }
  74. }
  75. }
  76. }
  77. }
  78. fun stop() {
  79. if (p != null) {
  80. p!!.inputStream.close()
  81. p!!.errorStream.close()
  82. p!!.destroy()
  83. p = null
  84. }
  85. if (script != null) {
  86. script!!.delete()
  87. script = null
  88. }
  89. }
  90. }
  91. }