¿Cómo obtener un contenido manifiesto válido y confiable del archivo APK, incluso usando InputStream?

9

Antecedentes

Quería obtener información sobre los archivos APK (incluidos los archivos APK divididos), incluso si están dentro de archivos zip comprimidos (sin descomprimirlos). En mi caso, esto incluye varias cosas, como el nombre del paquete, el código de la versión, el nombre de la versión, la etiqueta de la aplicación, el ícono de la aplicación y si es un archivo APK dividido o no.

Tenga en cuenta que quiero hacerlo todo dentro de una aplicación de Android, no usando una PC, por lo que es posible que algunas herramientas no se puedan usar.

El problema

Esto significa que no puedo usar la función getPackageArchiveInfo , ya que esta función requiere una ruta al archivo APK y solo funciona en archivos apk no divididos.

En resumen, no hay una función de marco para hacerlo, así que tengo que encontrar una forma de hacerlo yendo al archivo comprimido, usando InputStream como entrada para analizarlo en una función.

Hay varias soluciones en línea, incluso fuera de Android, pero no sé cuál es estable y funciona en todos los casos. Muchos pueden ser buenos incluso para Android (ejemplo aquí ), pero pueden fallar el análisis y pueden requerir una ruta de archivo en lugar de Uri / InputStream.

Lo que he encontrado y probado

Encontré esto en StackOverflow, pero lamentablemente de acuerdo con mis pruebas, siempre genera contenido, pero en algunos casos raros no es un contenido XML válido.

Hasta ahora, he encontrado estos nombres de paquetes de aplicaciones y sus códigos de versión que el analizador no puede analizar, ya que el contenido XML de salida no es válido:

  1. com.farproc.wifi.analyzer 139
  2. com.teslacoilsw.launcherclientproxy 2
  3. com.hotornot.app 3072
  4. Android 29 (esa es la aplicación del sistema "Sistema Android" en sí)
  5. com.google.android.videos 41300042
  6. com.facebook.katana 201518851
  7. com.keramidas.TitaniumBackupPro 10
  8. com.google.android.apps.tachyon 2985033
  9. com.google.android.apps.photos 3594753

Usando un visor XML y un validador XML , estos son los problemas con estas aplicaciones:

  • Para el n. ° 1, n. ° 2, comencé con un contenido muy extraño <mnfs.
  • Para el # 3, no le gusta el "&" en <activity theme="resourceID 0x7f13000b" label="Features & Tests" ...
  • Para el # 4, se perdió la etiqueta final de "manifiesto" al final.
  • Para el n. ° 5, omitió varias etiquetas finales, al menos "intento de filtro", "receptor" y "manifiesto". Quizás más.
  • Para el # 6, obtuvo el atributo "allowBackup" dos veces en la etiqueta "application" por alguna razón.
  • Para # 7, que tiene un valor sin atributo en la etiqueta manifiesta: <manifest versionCode="resourceID 0xa" ="1.3.2".
  • Para el n. ° 8, se perdió mucho contenido después de obtener algunas etiquetas de "usos-función", y no tenía una etiqueta final para "manifiesto".
  • Para el # 9, se perdió mucho contenido después de obtener algunas etiquetas de "usos-permiso", y no tenía una etiqueta final para "manifiesto"

Sorprendentemente, no encontré ningún problema con los archivos APK divididos. Solo con los archivos APK principales.

Aquí está el código (también disponible aquí ):

MainActivity .kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        thread {
            val problematicApkFiles = HashMap<ApplicationInfo, HashSet<String>>()
            val installedApplications = packageManager.getInstalledPackages(0)
            val startTime = System.currentTimeMillis()
            for ((index, packageInfo) in installedApplications.withIndex()) {
                val applicationInfo = packageInfo.applicationInfo
                val packageName = packageInfo.packageName
//                Log.d("AppLog", "$index/${installedApplications.size} parsing app $packageName ${packageInfo.versionCode}...")
                val mainApkFilePath = applicationInfo.publicSourceDir
                val parsedManifestOfMainApkFile =
                        try {
                            val parsedManifest = ManifestParser.parse(mainApkFilePath)
                            if (parsedManifest?.isSplitApk != false)
                                Log.e("AppLog", "$packageName - parsed normal APK, but failed to identify it as such")
                            parsedManifest?.manifestAttributes
                        } catch (e: Exception) {
                            Log.e("AppLog", e.toString())
                            null
                        }
                if (parsedManifestOfMainApkFile == null) {
                    problematicApkFiles.getOrPut(applicationInfo, { HashSet() }).add(mainApkFilePath)
                    Log.e("AppLog", "$packageName - failed to parse main APK file $mainApkFilePath")
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                    applicationInfo.splitPublicSourceDirs?.forEach {
                        val parsedManifestOfSplitApkFile =
                                try {
                                    val parsedManifest = ManifestParser.parse(it)
                                    if (parsedManifest?.isSplitApk != true)
                                        Log.e("AppLog", "$packageName - parsed split APK, but failed to identify it as such")
                                    parsedManifest?.manifestAttributes
                                } catch (e: Exception) {
                                    Log.e("AppLog", e.toString())
                                    null
                                }
                        if (parsedManifestOfSplitApkFile == null) {
                            Log.e("AppLog", "$packageName - failed to parse main APK file $it")
                            problematicApkFiles.getOrPut(applicationInfo, { HashSet() }).add(it)
                        }
                    }
            }
            val endTime = System.currentTimeMillis()
            Log.d("AppLog", "done parsing. number of files we failed to parse:${problematicApkFiles.size} time taken:${endTime - startTime} ms")
            if (problematicApkFiles.isNotEmpty()) {
                Log.d("AppLog", "list of files that we failed to get their manifest:")
                for (entry in problematicApkFiles) {
                    Log.d("AppLog", "packageName:${entry.key.packageName} , files:${entry.value}")
                }
            }
        }
    }
}

ManifestParser.kt

class ManifestParser{
    var isSplitApk: Boolean? = null
    var manifestAttributes: HashMap<String, String>? = null

    companion object {
        fun parse(file: File) = parse(java.io.FileInputStream(file))
        fun parse(filePath: String) = parse(File(filePath))
        fun parse(inputStream: InputStream): ManifestParser? {
            val result = ManifestParser()
            val manifestXmlString = ApkManifestFetcher.getManifestXmlFromInputStream(inputStream)
                    ?: return null
            val factory: DocumentBuilderFactory = DocumentBuilderFactory.newInstance()
            val builder: DocumentBuilder = factory.newDocumentBuilder()
            val document: Document? = builder.parse(manifestXmlString.byteInputStream())
            if (document != null) {
                document.documentElement.normalize()
                val manifestNode: Node? = document.getElementsByTagName("manifest")?.item(0)
                if (manifestNode != null) {
                    val manifestAttributes = HashMap<String, String>()
                    for (i in 0 until manifestNode.attributes.length) {
                        val node = manifestNode.attributes.item(i)
                        manifestAttributes[node.nodeName] = node.nodeValue
                    }
                    result.manifestAttributes = manifestAttributes
                }
            }
            result.manifestAttributes?.let {
                result.isSplitApk = (it["android:isFeatureSplit"]?.toBoolean()
                        ?: false) || (it.containsKey("split"))
            }
            return result
        }

    }
}

ApkManifestFetcher.kt

object ApkManifestFetcher {
    fun getManifestXmlFromFile(apkFile: File) = getManifestXmlFromInputStream(FileInputStream(apkFile))
    fun getManifestXmlFromFilePath(apkFilePath: String) = getManifestXmlFromInputStream(FileInputStream(File(apkFilePath)))
    fun getManifestXmlFromInputStream(ApkInputStream: InputStream): String? {
        ZipInputStream(ApkInputStream).use { zipInputStream: ZipInputStream ->
            while (true) {
                val entry = zipInputStream.nextEntry ?: break
                if (entry.name == "AndroidManifest.xml") {
//                    zip.getInputStream(entry).use { input ->
                    return decompressXML(zipInputStream.readBytes())
//                    }
                }
            }
        }
        return null
    }

    /**
     * Binary XML doc ending Tag
     */
    private var endDocTag = 0x00100101

    /**
     * Binary XML start Tag
     */
    private var startTag = 0x00100102

    /**
     * Binary XML end Tag
     */
    private var endTag = 0x00100103


    /**
     * Reference var for spacing
     * Used in prtIndent()
     */
    private var spaces = "                                             "

    /**
     * Parse the 'compressed' binary form of Android XML docs
     * such as for AndroidManifest.xml in .apk files
     * Source: http://stackoverflow.com/questions/2097813/how-to-parse-the-androidmanifest-xml-file-inside-an-apk-package/4761689#4761689
     *
     * @param xml Encoded XML content to decompress
     */
    private fun decompressXML(xml: ByteArray): String {

        val resultXml = StringBuilder()

        // Compressed XML file/bytes starts with 24x bytes of data,
        // 9 32 bit words in little endian order (LSB first):
        //   0th word is 03 00 08 00
        //   3rd word SEEMS TO BE:  Offset at then of StringTable
        //   4th word is: Number of strings in string table
        // WARNING: Sometime I indiscriminently display or refer to word in
        //   little endian storage format, or in integer format (ie MSB first).
        val numbStrings = lew(xml, 4 * 4)

        // StringIndexTable starts at offset 24x, an array of 32 bit LE offsets
        // of the length/string data in the StringTable.
        val sitOff = 0x24  // Offset of start of StringIndexTable

        // StringTable, each string is represented with a 16 bit little endian
        // character count, followed by that number of 16 bit (LE) (Unicode) chars.
        val stOff = sitOff + numbStrings * 4  // StringTable follows StrIndexTable

        // XMLTags, The XML tag tree starts after some unknown content after the
        // StringTable.  There is some unknown data after the StringTable, scan
        // forward from this point to the flag for the start of an XML start tag.
        var xmlTagOff = lew(xml, 3 * 4)  // Start from the offset in the 3rd word.
        // Scan forward until we find the bytes: 0x02011000(x00100102 in normal int)
        run {
            var ii = xmlTagOff
            while (ii < xml.size - 4) {
                if (lew(xml, ii) == startTag) {
                    xmlTagOff = ii
                    break
                }
                ii += 4
            }
        } // end of hack, scanning for start of first start tag

        // XML tags and attributes:
        // Every XML start and end tag consists of 6 32 bit words:
        //   0th word: 02011000 for startTag and 03011000 for endTag
        //   1st word: a flag?, like 38000000
        //   2nd word: Line of where this tag appeared in the original source file
        //   3rd word: FFFFFFFF ??
        //   4th word: StringIndex of NameSpace name, or FFFFFFFF for default NS
        //   5th word: StringIndex of Element Name
        //   (Note: 01011000 in 0th word means end of XML document, endDocTag)

        // Start tags (not end tags) contain 3 more words:
        //   6th word: 14001400 meaning??
        //   7th word: Number of Attributes that follow this tag(follow word 8th)
        //   8th word: 00000000 meaning??

        // Attributes consist of 5 words:
        //   0th word: StringIndex of Attribute Name's Namespace, or FFFFFFFF
        //   1st word: StringIndex of Attribute Name
        //   2nd word: StringIndex of Attribute Value, or FFFFFFF if ResourceId used
        //   3rd word: Flags?
        //   4th word: str ind of attr value again, or ResourceId of value

        // TMP, dump string table to tr for debugging
        //tr.addSelect("strings", null);
        //for (int ii=0; ii<numbStrings; ii++) {
        //  // Length of string starts at StringTable plus offset in StrIndTable
        //  String str = compXmlString(xml, sitOff, stOff, ii);
        //  tr.add(String.valueOf(ii), str);
        //}
        //tr.parent();

        // Step through the XML tree element tags and attributes
        var off = xmlTagOff
        var indent = 0
//        var startTagLineNo = -2
        while (off < xml.size) {
            val tag0 = lew(xml, off)
            //int tag1 = LEW(xml, off+1*4);
//            val lineNo = lew(xml, off + 2 * 4)
            //int tag3 = LEW(xml, off+3*4);
//            val nameNsSi = lew(xml, off + 4 * 4)
            val nameSi = lew(xml, off + 5 * 4)

            if (tag0 == startTag) { // XML START TAG
//                val tag6 = lew(xml, off + 6 * 4)  // Expected to be 14001400
                val numbAttrs = lew(xml, off + 7 * 4)  // Number of Attributes to follow
                //int tag8 = LEW(xml, off+8*4);  // Expected to be 00000000
                off += 9 * 4  // Skip over 6+3 words of startTag data
                val name = compXmlString(xml, sitOff, stOff, nameSi)
                //tr.addSelect(name, null);
//                startTagLineNo = lineNo

                // Look for the Attributes
                val sb = StringBuffer()
                for (ii in 0 until numbAttrs) {
//                    val attrNameNsSi = lew(xml, off)  // AttrName Namespace Str Ind, or FFFFFFFF
                    val attrNameSi = lew(xml, off + 1 * 4)  // AttrName String Index
                    val attrValueSi = lew(xml, off + 2 * 4) // AttrValue Str Ind, or FFFFFFFF
//                    val attrFlags = lew(xml, off + 3 * 4)
                    val attrResId = lew(xml, off + 4 * 4)  // AttrValue ResourceId or dup AttrValue StrInd
                    off += 5 * 4  // Skip over the 5 words of an attribute

                    val attrName = compXmlString(xml, sitOff, stOff, attrNameSi)
                    val attrValue = if (attrValueSi != -1)
                        compXmlString(xml, sitOff, stOff, attrValueSi)
                    else
                        "resourceID 0x" + Integer.toHexString(attrResId)
                    sb.append(" $attrName=\"$attrValue\"")
                    //tr.add(attrName, attrValue);
                }
                resultXml.append(prtIndent(indent, "<$name$sb>"))
                indent++

            } else if (tag0 == endTag) { // XML END TAG
                indent--
                off += 6 * 4  // Skip over 6 words of endTag data
                val name = compXmlString(xml, sitOff, stOff, nameSi)
                resultXml.append(prtIndent(indent, "</$name>")) //  (line $startTagLineNo-$lineNo)
                //tr.parent();  // Step back up the NobTree

            } else if (tag0 == endDocTag) {  // END OF XML DOC TAG
                break

            } else {
//                println("  Unrecognized tag code '" + Integer.toHexString(tag0)
//                        + "' at offset " + off
//                )
                break
            }
        } // end of while loop scanning tags and attributes of XML tree
//        println("    end at offset $off")

        return resultXml.toString()
    } // end of decompressXML


    /**
     * Tool Method for decompressXML();
     * Compute binary XML to its string format
     * Source: Source: http://stackoverflow.com/questions/2097813/how-to-parse-the-androidmanifest-xml-file-inside-an-apk-package/4761689#4761689
     *
     * @param xml Binary-formatted XML
     * @param sitOff
     * @param stOff
     * @param strInd
     * @return String-formatted XML
     */
    private fun compXmlString(xml: ByteArray, @Suppress("SameParameterValue") sitOff: Int, stOff: Int, strInd: Int): String? {
        if (strInd < 0) return null
        val strOff = stOff + lew(xml, sitOff + strInd * 4)
        return compXmlStringAt(xml, strOff)
    }


    /**
     * Tool Method for decompressXML();
     * Apply indentation
     *
     * @param indent Indentation level
     * @param str String to indent
     * @return Indented string
     */
    private fun prtIndent(indent: Int, str: String): String {

        return spaces.substring(0, min(indent * 2, spaces.length)) + str
    }


    /**
     * Tool method for decompressXML()
     * Return the string stored in StringTable format at
     * offset strOff.  This offset points to the 16 bit string length, which
     * is followed by that number of 16 bit (Unicode) chars.
     *
     * @param arr StringTable array
     * @param strOff Offset to get string from
     * @return String from StringTable at offset strOff
     */
    private fun compXmlStringAt(arr: ByteArray, strOff: Int): String {
        val strLen = (arr[strOff + 1] shl (8 and 0xff00)) or (arr[strOff].toInt() and 0xff)
        val chars = ByteArray(strLen)
        for (ii in 0 until strLen) {
            chars[ii] = arr[strOff + 2 + ii * 2]
        }
        return String(chars)  // Hack, just use 8 byte chars
    } // end of compXmlStringAt


    /**
     * Return value of a Little Endian 32 bit word from the byte array
     * at offset off.
     *
     * @param arr Byte array with 32 bit word
     * @param off Offset to get word from
     * @return Value of Little Endian 32 bit word specified
     */
    private fun lew(arr: ByteArray, off: Int): Int {
        return (arr[off + 3] shl 24 and -0x1000000 or ((arr[off + 2] shl 16) and 0xff0000)
                or (arr[off + 1] shl 8 and 0xff00) or (arr[off].toInt() and 0xFF))
    } // end of LEW

    private infix fun Byte.shl(i: Int): Int = (this.toInt() shl i)
//    private infix fun Int.shl(i: Int): Int = (this shl i)
}

Las preguntas

  1. ¿Cómo es que obtengo un contenido XML no válido para algunos archivos de manifiesto APK (por lo tanto, el análisis XML no funciona)?
  2. ¿Cómo puedo hacer que funcione siempre?
  3. ¿Hay una mejor manera de analizar el archivo de manifiesto en un XML válido? ¿Tal vez una mejor alternativa, que podría funcionar con todo tipo de archivos APK, incluidos los archivos comprimidos internos, sin descomprimirlos?
desarrollador de Android
fuente
Creo que algunos de los manifiestos están ofuscados por DexGuard (ver aquí ) donde se menciona la ofuscación de archivos de manifiesto. Este parece ser el caso para el # 1 en su lista, com.farproc.wifi.analyzer. Su archivo de manifiesto comienza con "<mnfs" en lugar de "<manifiesto" y también otras 20 aplicaciones en mi teléfono.
Cheticamp
@Cheticamp Aún así, el marco en sí mismo puede leerlo bien. Esos son todos los archivos APK que están bien instalados en mi dispositivo. Algunos no tenían este problema exacto que usted describe, y uno de ellos es extremadamente antiguo.
Desarrollador de Android
Y, sin embargo, DexGuard afirma poder ofuscar el archivo de manifiesto. No sé cómo lo hacen y todavía tengo el marco de trabajo leer el manifiesto, pero es un área para mirar en la OMI. En cuanto a los otros problemas, ¿ha estudiado el uso de XmlPullParser para extraer justo lo que necesita? Tal vez ya intentaste esto y no leí con suficiente atención.
Cheticamp
Ya mencioné todos los problemas que he encontrado, y no es "mnfs" para la mayoría de los casos. Es solo para los primeros 2 casos. Además, si intenta analizarlos a través de alguna herramienta en línea, seguirá funcionando bien.
Desarrollador de Android
¿Qué no funciona con apk-parser ? Pude ejecutarlo en un emulador y funcionó bien. ¿Sería necesario aceptar un InputStream?
Cheticamp

Respuestas:

0

Probablemente tendrías que manejar todos los casos especiales que ya has identificado.

Los alias y las referencias hexadecimales pueden confundirlo; estos tendrían que ser resueltos.

Por ejemplo, retroceder de manifesta mnfsal menos resolvería un problema:

fun getRootNode(document: Document): Node? {
    var node: Node? = document.getElementsByTagName("manifest")?.item(0)
    if (node == null) {
        node = document.getElementsByTagName("mnfs")?.item(0)
    }
    return node
}

"Características y pruebas" requeriría TextUtils.htmlEncode()para &amp;u otra configuración del analizador.

Hacer que analice AndroidManifest.xmlarchivos individuales facilitaría la prueba, ya que con cada paquete puede haber una entrada más inesperada, hasta que se acerque al analizador de manifiesto que usa el sistema operativo (el código fuente podría ayudar). Como se puede ver, puede establecer cookies para leerlo. Tome esta lista de nombres de paquetes y configure un caso de prueba para cada uno de ellos, luego los problemas están bastante aislados. Pero el problema principal es que estas cookies probablemente no estén disponibles para aplicaciones de terceros.

Martin Zeitler
fuente
No es solo eso, sino que, como escribí, el XML en sí no es válido. El problema es incluso antes de analizar el XML. Significado: algunas etiquetas no existen, y algunas no tienen etiquetas finales. Por favor, si ha encontrado una manera de solucionar este problema, dígame cómo.
Desarrollador de Android
0

Parece que ApkManifestFetcher no maneja todos los casos, como el texto (entre etiquetas) y las declaraciones de espacio de nombres y, tal vez, algunas otras cosas. A continuación se muestra una revisión de ApkManifestFetcher que maneja todos los más de 300 APK en mi teléfono, excepto el APK de Netflix que presenta algunos atributos en blanco.

Ya no creo que los archivos que comienzan <mnfstienen algo que ver con la ofuscación, sino que están codificados con UTF-8 en lugar de UTF-16, que la aplicación supone (16 bits frente a 8 bits). La aplicación modificada maneja la codificación UTF-8 y puede analizar estos archivos.

Como se mencionó anteriormente, los espacios de nombres no son manejados correctamente por la clase original o este retrabajo, aunque el retrabajo puede pasarlos por alto. Los comentarios en el código describen esto un poco.

Dicho esto, el siguiente código puede ser lo suficientemente bueno para ciertas aplicaciones. El mejor, aunque más largo, curso de acción sería usar el código de apktool, que parece ser capaz de manejar todos los APK.

ApkManifestFetcher

object ApkManifestFetcher {
    fun getManifestXmlFromFile(apkFile: File) =
            getManifestXmlFromInputStream(FileInputStream(apkFile))

    fun getManifestXmlFromFilePath(apkFilePath: String) =
            getManifestXmlFromInputStream(FileInputStream(File(apkFilePath)))

    fun getManifestXmlFromInputStream(ApkInputStream: InputStream): String? {
        ZipInputStream(ApkInputStream).use { zipInputStream: ZipInputStream ->
            while (true) {
                val entry = zipInputStream.nextEntry ?: break
                if (entry.name == "AndroidManifest.xml") {
                    return decompressXML(zipInputStream.readBytes())
                }
            }
        }
        return null
    }

    /**
     * Binary XML name space starts
     */
    private const val startNameSpace = 0x00100100

    /**
     * Binary XML name space ends
     */
    private const val endNameSpace = 0x00100101

    /**
     * Binary XML start Tag
     */
    private const val startTag = 0x00100102

    /**
     * Binary XML end Tag
     */
    private const val endTag = 0x00100103

    /**
     * Binary XML text Tag
     */
    private const val textTag = 0x00100104

    /*
     * Flag for UTF-8 encoded file. Default is UTF-16.
     */
    private const val FLAG_UTF_8 = 0x00000100

    /**
     * Reference var for spacing
     * Used in prtIndent()
     */
    private const val spaces = "                                             "

    // Flag if the manifest is in UTF-8 but we don't really handle it.
    private var mIsUTF8 = false

    /**
     * Parse the 'compressed' binary form of Android XML docs
     * such as for AndroidManifest.xml in .apk files
     * Source: http://stackoverflow.com/questions/2097813/how-to-parse-the-androidmanifest-xml-file-inside-an-apk-package/4761689#4761689
     *
     * @param xml Encoded XML content to decompress
     */
    private fun decompressXML(xml: ByteArray): String {
        val resultXml = StringBuilder()
        /*
        Compressed XML file/bytes starts with 24x bytes of data
            9 32 bit words in little endian order (LSB first):
                0th word is 03 00 (Magic number) 08 00 (header size words 0-1)
                1st word is the size of the compressed XML. This should equal size of xml array.
                2nd word is 01 00 (Magic number) 1c 00 (header size words 2-8)
                3rd word is offset of byte after string table
                4th word is number of strings in string table
                5th word is style count
                6th word are flags
                7th word string table offset
                8th word is styles offset
                [string index table (little endian offset into string table)]
                [string table (two byte length followed by text for each entry UTF-16, nul)]
        */

        mIsUTF8 = (lew(xml, 24) and FLAG_UTF_8) != 0

        val numbStrings = lew(xml, 4 * 4)

        // StringIndexTable starts at offset 24x, an array of 32 bit LE offsets
        // of the length/string data in the StringTable.
        val sitOff = 0x24  // Offset of start of StringIndexTable

        // StringTable, each string is represented with a 16 bit little endian
        // character count, followed by that number of 16 bit (LE) (Unicode) chars.
        val stOff = sitOff + numbStrings * 4  // StringTable follows StrIndexTable

        // XMLTags, The XML tag tree starts after some unknown content after the
        // StringTable.  There is some unknown data after the StringTable, scan
        // forward from this point to the flag for the start of an XML start tag.
        var xmlTagOff = lew(xml, 3 * 4)  // Start from the offset in the 3rd word.
        // Scan forward until we find the bytes: 0x02011000(x00100102 in normal int)
        run {
            var ii = xmlTagOff
            while (ii < xml.size - 4) {
                if (lew(xml, ii) == startTag) {
                    xmlTagOff = ii
                    break
                }
                ii += 4
            }
        }

        /*
        XML tags and attributes:

        Every XML start and end tag consists of 6 32 bit words:
            0th word: 02011000 for startTag and 03011000 for endTag
            1st word: a flag?, like 38000000
            2nd word: Line of where this tag appeared in the original source file
            3rd word: 0xFFFFFFFF ??
            4th word: StringIndex of NameSpace name, or 0xFFFFFF for default NS
            5th word: StringIndex of Element Name
            (Note: 01011000 in 0th word means end of XML document, endDocTag)

        Start tags (not end tags) contain 3 more words:
            6th word: 14001400 meaning??
            7th word: Number of Attributes that follow this tag(follow word 8th)
            8th word: 00000000 meaning??

        Attributes consist of 5 words:
            0th word: StringIndex of Attribute Name's Namespace, or 0xFFFFFF
            1st word: StringIndex of Attribute Name
            2nd word: StringIndex of Attribute Value, or 0xFFFFFFF if ResourceId used
            3rd word: Flags?
            4th word: str ind of attr value again, or ResourceId of value

        Text blocks consist of 7 words
            0th word: The text tag (0x00100104)
            1st word: Size of the block (28 bytes)
            2nd word: Line number
            3rd word: 0xFFFFFFFF
            4th word: Index into the string table
            5th word: Unknown
            6th word: Unknown

        startNameSpace blocks consist of 6 words
            0th word: The startNameSpace tag (0x00100100)
            1st word: Size of the block (24 bytes)
            2nd word: Line number
            3rd word: 0xFFFFFFFF
            4th word: Index into the string table for the prefix
            5th word: Index into the string table for the URI

        endNameSpace blocks consist of 6 words
            0th word: The endNameSpace tag (0x00100101)
            1st word: Size of the block (24 bytes)
            2nd word: Line number
            3rd word: 0xFFFFFFFF
            4th word: Index into the string table for the prefix
            5th word: Index into the string table for the URI
        */

        // Step through the XML tree element tags and attributes
        var off = xmlTagOff
        var indent = 0
        while (off < xml.size) {
            val tag0 = lew(xml, off)
            val nameSi = lew(xml, off + 5 * 4)

            when (tag0) {
                startTag -> {
                    val numbAttrs = lew(xml, off + 7 * 4)  // Number of Attributes to follow
                    off += 9 * 4  // Skip over 6+3 words of startTag data
                    val name = compXmlString(xml, sitOff, stOff, nameSi)

                    // Look for the Attributes
                    val sb = StringBuffer()
                    for (ii in 0 until numbAttrs) {
                        val attrNameSi = lew(xml, off + 1 * 4)  // AttrName String Index
                        val attrValueSi = lew(xml, off + 2 * 4) // AttrValue Str Ind, or 0xFFFFFF
                        val attrResId = lew(xml, off + 4 * 4)  // AttrValue ResourceId or dup AttrValue StrInd
                        off += 5 * 4  // Skip over the 5 words of an attribute

                        val attrName = compXmlString(xml, sitOff, stOff, attrNameSi)
                        val attrValue = if (attrValueSi != -1)
                            compXmlString(xml, sitOff, stOff, attrValueSi)
                        else
                            "resourceID 0x" + Integer.toHexString(attrResId)
                        sb.append(" $attrName=\"$attrValue\"")
                    }
                    resultXml.append(prtIndent(indent, "<$name$sb>"))
                    indent++
                }
                endTag -> {
                    indent--
                    off += 6 * 4  // Skip over 6 words of endTag data
                    val name = compXmlString(xml, sitOff, stOff, nameSi)
                    resultXml.append(prtIndent(indent, "</$name>")
                    )

                }
                textTag -> {  // Text that is hanging out between start and end tags
                    val text = compXmlString(xml, sitOff, stOff, lew(xml, off + 16))
                    resultXml.append(text)
                    off += lew(xml, off + 4)
                }
                startNameSpace -> {
                    //Todo startNameSpace and endNameSpace are effectively skipped, but they are not handled.
                    off += lew(xml, off + 4)
                }
                endNameSpace -> {
                    off += lew(xml, off + 4)
                }
                else -> {
                    Log.d(
                            "Applog", "  Unrecognized tag code '" + Integer.toHexString(tag0)
                            + "' at offset " + off
                    )
                }
            }
        }
        return resultXml.toString()
    }

    /**
     * Tool Method for decompressXML();
     * Compute binary XML to its string format
     * Source: Source: http://stackoverflow.com/questions/2097813/how-to-parse-the-androidmanifest-xml-file-inside-an-apk-package/4761689#4761689
     *
     * @param xml Binary-formatted XML
     * @param sitOff
     * @param stOff
     * @param strInd
     * @return String-formatted XML
     */
    private fun compXmlString(
            xml: ByteArray, @Suppress("SameParameterValue") sitOff: Int,
            stOff: Int,
            strInd: Int
    ): String? {
        if (strInd < 0) return null
        val strOff = stOff + lew(xml, sitOff + strInd * 4)
        return compXmlStringAt(xml, strOff)
    }

    /**
     * Tool Method for decompressXML();
     * Apply indentation
     *
     * @param indent Indentation level
     * @param str String to indent
     * @return Indented string
     */
    private fun prtIndent(indent: Int, str: String): String {
        return spaces.substring(0, min(indent * 2, spaces.length)) + str
    }

    /**
     * Tool method for decompressXML()
     * Return the string stored in StringTable format at
     * offset strOff.  This offset points to the 16 bit string length, which
     * is followed by that number of 16 bit (Unicode) chars.
     *
     * @param arr StringTable array
     * @param strOff Offset to get string from
     * @return String from StringTable at offset strOff
     */
    private fun compXmlStringAt(arr: ByteArray, strOff: Int): String {
        var start = strOff
        var charSetUsed: Charset = Charsets.UTF_16LE

        val byteLength = if (mIsUTF8) {
            charSetUsed = Charsets.UTF_8
            start += 2
            arr[strOff + 1].toInt() and 0xFF
        } else { // UTF-16LE
            start += 2
            ((arr[strOff + 1].toInt() and 0xFF shl 8) or (arr[strOff].toInt() and 0xFF)) * 2
        }
        return String(arr, start, byteLength, charSetUsed)
    }

    /**
     * Return value of a Little Endian 32 bit word from the byte array
     * at offset off.
     *
     * @param arr Byte array with 32 bit word
     * @param off Offset to get word from
     * @return Value of Little Endian 32 bit word specified
     */
    private fun lew(arr: ByteArray, off: Int): Int {
        return (arr[off + 3] shl 24 and -0x1000000 or ((arr[off + 2] shl 16) and 0xff0000)
                or (arr[off + 1] shl 8 and 0xff00) or (arr[off].toInt() and 0xFF))
    }

    private infix fun Byte.shl(i: Int): Int = (this.toInt() shl i)
}
Cheticamp
fuente
Entonces todavía no es confiable. ¿Has probado quizás jadx? Me pregunto si este puede manejar bien los archivos APK incluso en la aplicación de Android.
Desarrollador de Android
@androiddeveloper No he mirado en jadx. He leído Apktool y creo que es una buena fuente (y abierta). Haría falta un poco de trabajo alojarlo en Android, pero tal vez solo la parte del manifiesto sería factible. Lo que se publica aquí definitivamente no es digno de producción, ya que hay muchos aspectos de los archivos de manifiesto que no se abordan.
Cheticamp
@androiddeveloper Creo que los manifiestos que comienzan con "<mnfs" están codificados en UTF-8 en lugar de UTF-16 y la aplicación asume UTF-16. Es por eso que es "mnfs" - "m (a) n (i) f (e) s (t)" a, i, e, t se caen ya que se supone que 16 bits.
Cheticamp
jadx también es de código abierto, y también en Java. Sin embargo, no estoy seguro de si es compatible con InputStream (como pregunté). Si encuentra una buena solución, hágamelo saber. Ya probé varias soluciones y no encontré ninguna confiable. También tengo miedo de usar las herramientas grandes, porque tal vez podrían tomar demasiada memoria, lo que podría causar un bloqueo en algunos dispositivos (jadx habla de OOM en sus preguntas frecuentes: github.com/skylot/jadx/wiki/Troubleshooting-Q&A ) . Así que prefiero una solución / biblioteca mínima que funcione mejor para Android.
desarrollador de Android