summaryrefslogtreecommitdiff
path: root/packages/StatementService/src/com/android/statementservice/utils/StatementUtils.kt
blob: 92d752c83a9f30095f2a55ff62394e55b4b62be9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
/*
 * Copyright (C) 2021 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.statementservice.utils

import android.content.Context
import android.content.pm.PackageManager
import android.util.Patterns
import com.android.statementservice.retriever.Relation
import java.net.URL
import java.security.MessageDigest

internal object StatementUtils {

    /**
     * Field name for namespace.
     */
    const val NAMESPACE_FIELD = "namespace"

    /**
     * Supported asset namespaces.
     */
    const val NAMESPACE_WEB = "web"
    const val NAMESPACE_ANDROID_APP = "android_app"

    /**
     * Field names in a web asset descriptor.
     */
    const val WEB_ASSET_FIELD_SITE = "site"

    /**
     * Field names in a Android app asset descriptor.
     */
    const val ANDROID_APP_ASSET_FIELD_PACKAGE_NAME = "package_name"
    const val ANDROID_APP_ASSET_FIELD_CERT_FPS = "sha256_cert_fingerprints"

    /**
     * Field names in a statement.
     */
    const val ASSET_DESCRIPTOR_FIELD_RELATION = "relation"
    const val ASSET_DESCRIPTOR_FIELD_TARGET = "target"
    const val DELEGATE_FIELD_DELEGATE = "include"

    val HEX_DIGITS =
        charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F')

    val RELATION by lazy { Relation.create("delegate_permission/common.handle_all_urls") }
    private const val ANDROID_ASSET_FORMAT =
        """{"namespace": "android_app", "package_name": "%s", "sha256_cert_fingerprints": [%s]}"""
    private const val WEB_ASSET_FORMAT = """{"namespace": "web", "site": "%s"}"""

    private val digesterSha256 by lazy { tryOrNull { MessageDigest.getInstance("SHA-256") } }

    internal inline fun <T> tryOrNull(block: () -> T) =
        try {
            block()
        } catch (ignored: Exception) {
            null
        }

    /**
     * Returns the normalized sha-256 fingerprints of a given package according to the Android
     * package manager.
     */
    fun getCertFingerprintsFromPackageManager(
        context: Context,
        packageName: String
    ): Result<List<String>> {
        val signingInfo = try {
            context.packageManager.getPackageInfo(
                packageName,
                PackageManager.GET_SIGNING_CERTIFICATES or PackageManager.MATCH_ANY_USER
            )
                .signingInfo
        } catch (e: Exception) {
            return Result.Failure(e)
        }
        return if (signingInfo.hasMultipleSigners()) {
            signingInfo.apkContentsSigners
        } else {
            signingInfo.signingCertificateHistory
        }.map {
            val result = computeNormalizedSha256Fingerprint(it.toByteArray())
            if (result is Result.Failure) {
                return result.asType()
            } else {
                (result as Result.Success).value
            }
        }.let { Result.Success(it) }
    }

    /**
     * Computes the hash of the byte array using the specified algorithm, returning a hex string
     * with a colon between each byte.
     */
    fun computeNormalizedSha256Fingerprint(signature: ByteArray) =
        digesterSha256?.digest(signature)
            ?.let(StatementUtils::bytesToHexString)
            ?.let { Result.Success(it) }
            ?: Result.Failure()

    private fun bytesToHexString(bytes: ByteArray): String {
        val hexChars = CharArray(bytes.size * 3 - 1)
        var bufIndex = 0
        for (index in bytes.indices) {
            val byte = bytes[index].toInt() and 0xFF
            if (index > 0) {
                hexChars[bufIndex++] = ':'
            }

            hexChars[bufIndex++] = HEX_DIGITS[byte ushr 4]
            hexChars[bufIndex++] = HEX_DIGITS[byte and 0x0F]
        }
        return String(hexChars)
    }

    fun createAndroidAssetString(context: Context, packageName: String): Result<String> {
        val result = getCertFingerprintsFromPackageManager(context, packageName)
        if (result is Result.Failure) {
            return result.asType()
        }
        return Result.Success(
            ANDROID_ASSET_FORMAT.format(
                packageName,
                (result as Result.Success).value.joinToString(separator = "\", \"")
            )
        )
    }

    fun createAndroidAsset(packageName: String, certFingerprints: List<String>) =
        String.format(
            ANDROID_ASSET_FORMAT,
            packageName,
            certFingerprints.joinToString(separator = ", ") { "\"$it\"" })

    fun createWebAssetString(scheme: String, host: String): Result<String> {
        if (!Patterns.DOMAIN_NAME.matcher(host).matches()) {
            return Result.Failure("Input host is not valid.")
        }
        if (scheme != "http" && scheme != "https") {
            return Result.Failure("Input scheme is not valid.")
        }
        return Result.Success(WEB_ASSET_FORMAT.format(URL(scheme, host, "").toString()))
    }

    // Hosts with *. for wildcard subdomain support are verified against their root domain
    fun createWebAssetString(host: String) =
        WEB_ASSET_FORMAT.format(URL("https", host.removePrefix("*."), "").toString())
}