1/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#include "keystore_attestation_id.h"
17
18#define LOG_TAG "keystore_att_id"
19
20#include <cutils/log.h>
21
22#include <memory>
23#include <string>
24#include <vector>
25
26#include <binder/IServiceManager.h>
27#include <binder/Parcel.h>
28#include <binder/Parcelable.h>
29#include <binder/PersistableBundle.h>
30
31#include <android/security/keymaster/BpKeyAttestationApplicationIdProvider.h>
32#include <android/security/keymaster/IKeyAttestationApplicationIdProvider.h>
33#include <keystore/KeyAttestationApplicationId.h>
34#include <keystore/KeyAttestationPackageInfo.h>
35#include <keystore/Signature.h>
36
37#include <openssl/asn1t.h>
38#include <openssl/sha.h>
39
40#include <utils/String8.h>
41
42namespace android {
43
44namespace {
45
46static std::vector<uint8_t> signature2SHA256(const content::pm::Signature& sig) {
47    std::vector<uint8_t> digest_buffer(SHA256_DIGEST_LENGTH);
48    SHA256(sig.data().data(), sig.data().size(), digest_buffer.data());
49    return digest_buffer;
50}
51
52using ::android::security::keymaster::BpKeyAttestationApplicationIdProvider;
53
54class KeyAttestationApplicationIdProvider : public BpKeyAttestationApplicationIdProvider {
55  public:
56    KeyAttestationApplicationIdProvider();
57
58    static KeyAttestationApplicationIdProvider& get();
59
60  private:
61    android::sp<android::IServiceManager> service_manager_;
62};
63
64KeyAttestationApplicationIdProvider& KeyAttestationApplicationIdProvider::get() {
65    static KeyAttestationApplicationIdProvider mpm;
66    return mpm;
67}
68
69KeyAttestationApplicationIdProvider::KeyAttestationApplicationIdProvider()
70    : BpKeyAttestationApplicationIdProvider(
71          android::defaultServiceManager()->getService(String16("sec_key_att_app_id_provider"))) {}
72
73DECLARE_STACK_OF(ASN1_OCTET_STRING);
74
75typedef struct km_attestation_package_info {
76    ASN1_OCTET_STRING* package_name;
77    ASN1_INTEGER* version;
78} KM_ATTESTATION_PACKAGE_INFO;
79
80ASN1_SEQUENCE(KM_ATTESTATION_PACKAGE_INFO) = {
81    ASN1_SIMPLE(KM_ATTESTATION_PACKAGE_INFO, package_name, ASN1_OCTET_STRING),
82    ASN1_SIMPLE(KM_ATTESTATION_PACKAGE_INFO, version, ASN1_INTEGER),
83} ASN1_SEQUENCE_END(KM_ATTESTATION_PACKAGE_INFO);
84IMPLEMENT_ASN1_FUNCTIONS(KM_ATTESTATION_PACKAGE_INFO);
85
86DECLARE_STACK_OF(KM_ATTESTATION_PACKAGE_INFO);
87
88typedef struct km_attestation_application_id {
89    STACK_OF(KM_ATTESTATION_PACKAGE_INFO) * package_infos;
90    STACK_OF(ASN1_OCTET_STRING) * signature_digests;
91} KM_ATTESTATION_APPLICATION_ID;
92
93ASN1_SEQUENCE(KM_ATTESTATION_APPLICATION_ID) = {
94    ASN1_SET_OF(KM_ATTESTATION_APPLICATION_ID, package_infos, KM_ATTESTATION_PACKAGE_INFO),
95    ASN1_SET_OF(KM_ATTESTATION_APPLICATION_ID, signature_digests, ASN1_OCTET_STRING),
96} ASN1_SEQUENCE_END(KM_ATTESTATION_APPLICATION_ID);
97IMPLEMENT_ASN1_FUNCTIONS(KM_ATTESTATION_APPLICATION_ID);
98}
99
100}  // namespace android
101
102namespace std {
103template <> struct default_delete<android::KM_ATTESTATION_PACKAGE_INFO> {
104    void operator()(android::KM_ATTESTATION_PACKAGE_INFO* p) {
105        android::KM_ATTESTATION_PACKAGE_INFO_free(p);
106    }
107};
108template <> struct default_delete<ASN1_OCTET_STRING> {
109    void operator()(ASN1_OCTET_STRING* p) { ASN1_OCTET_STRING_free(p); }
110};
111template <> struct default_delete<android::KM_ATTESTATION_APPLICATION_ID> {
112    void operator()(android::KM_ATTESTATION_APPLICATION_ID* p) {
113        android::KM_ATTESTATION_APPLICATION_ID_free(p);
114    }
115};
116}  // namespace std
117
118namespace android {
119namespace security {
120namespace {
121
122using ::android::security::keymaster::KeyAttestationApplicationId;
123using ::android::security::keymaster::KeyAttestationPackageInfo;
124
125status_t build_attestation_package_info(const KeyAttestationPackageInfo& pinfo,
126    std::unique_ptr<KM_ATTESTATION_PACKAGE_INFO>* attestation_package_info_ptr) {
127
128    if (!attestation_package_info_ptr) return BAD_VALUE;
129    auto& attestation_package_info = *attestation_package_info_ptr;
130
131    attestation_package_info.reset(KM_ATTESTATION_PACKAGE_INFO_new());
132    if (!attestation_package_info.get()) return NO_MEMORY;
133
134    if (!pinfo.package_name()) {
135        ALOGE("Key attestation package info lacks package name");
136        return BAD_VALUE;
137    }
138
139    std::string pkg_name(String8(*pinfo.package_name()).string());
140    if (!ASN1_OCTET_STRING_set(attestation_package_info->package_name,
141                               reinterpret_cast<const unsigned char*>(pkg_name.data()),
142                               pkg_name.size())) {
143        return UNKNOWN_ERROR;
144    }
145
146    if (!ASN1_INTEGER_set(attestation_package_info->version, pinfo.version_code())) {
147        return UNKNOWN_ERROR;
148    }
149    return NO_ERROR;
150}
151
152StatusOr<std::vector<uint8_t>>
153build_attestation_application_id(const KeyAttestationApplicationId& key_attestation_id) {
154    auto attestation_id =
155        std::unique_ptr<KM_ATTESTATION_APPLICATION_ID>(KM_ATTESTATION_APPLICATION_ID_new());
156
157    auto attestation_pinfo_stack = reinterpret_cast<_STACK*>(attestation_id->package_infos);
158
159    if (key_attestation_id.pinfos_begin() == key_attestation_id.pinfos_end()) return BAD_VALUE;
160
161    for (auto pinfo = key_attestation_id.pinfos_begin(); pinfo != key_attestation_id.pinfos_end();
162         ++pinfo) {
163        if (!pinfo->package_name()) {
164            ALOGE("Key attestation package info lacks package name");
165            return BAD_VALUE;
166        }
167        std::string package_name(String8(*pinfo->package_name()).string());
168        std::unique_ptr<KM_ATTESTATION_PACKAGE_INFO> attestation_package_info;
169        auto rc = build_attestation_package_info(*pinfo, &attestation_package_info);
170        if (rc != NO_ERROR) {
171            ALOGE("Building DER attestation package info failed %d", rc);
172            return rc;
173        }
174        if (!sk_push(attestation_pinfo_stack, attestation_package_info.get())) {
175            return NO_MEMORY;
176        }
177        // if push succeeded, the stack takes ownership
178        attestation_package_info.release();
179    }
180
181    /** Apps can only share a uid iff they were signed with the same certificate(s). Because the
182     *  signature field actually holds the signing certificate, rather than a signature, we can
183     *  simply use the set of signature digests of the first package info.
184     */
185    const auto& pinfo = *key_attestation_id.pinfos_begin();
186    std::vector<std::vector<uint8_t>> signature_digests;
187
188    for (auto sig = pinfo.sigs_begin(); sig != pinfo.sigs_end(); ++sig) {
189        signature_digests.push_back(signature2SHA256(*sig));
190    }
191
192    auto signature_digest_stack = reinterpret_cast<_STACK*>(attestation_id->signature_digests);
193    for (auto si : signature_digests) {
194        auto asn1_item = std::unique_ptr<ASN1_OCTET_STRING>(ASN1_OCTET_STRING_new());
195        if (!asn1_item) return NO_MEMORY;
196        if (!ASN1_OCTET_STRING_set(asn1_item.get(), si.data(), si.size())) {
197            return UNKNOWN_ERROR;
198        }
199        if (!sk_push(signature_digest_stack, asn1_item.get())) {
200            return NO_MEMORY;
201        }
202        asn1_item.release();  // if push succeeded, the stack takes ownership
203    }
204
205    int len = i2d_KM_ATTESTATION_APPLICATION_ID(attestation_id.get(), nullptr);
206    if (len < 0) return UNKNOWN_ERROR;
207
208    std::vector<uint8_t> result(len);
209    uint8_t* p = result.data();
210    len = i2d_KM_ATTESTATION_APPLICATION_ID(attestation_id.get(), &p);
211    if (len < 0) return UNKNOWN_ERROR;
212
213    return result;
214}
215
216/* The following function are not used. They are mentioned here to silence
217 * warnings about them not being used.
218 */
219void unused_functions_silencer() __attribute__((unused));
220void unused_functions_silencer() {
221    i2d_KM_ATTESTATION_PACKAGE_INFO(nullptr, nullptr);
222    d2i_KM_ATTESTATION_APPLICATION_ID(nullptr, nullptr, 0);
223    d2i_KM_ATTESTATION_PACKAGE_INFO(nullptr, nullptr, 0);
224}
225
226}  // namespace
227
228StatusOr<std::vector<uint8_t>> gather_attestation_application_id(uid_t uid) {
229    auto& pm = KeyAttestationApplicationIdProvider::get();
230
231    /* Get the attestation application ID from package manager */
232    KeyAttestationApplicationId key_attestation_id;
233    auto status = pm.getKeyAttestationApplicationId(uid, &key_attestation_id);
234    if (!status.isOk()) {
235        ALOGE("package manager request for key attestation ID failed with: %s",
236              status.exceptionMessage().string());
237        return FAILED_TRANSACTION;
238    }
239
240    /* DER encode the attestation application ID */
241    return build_attestation_application_id(key_attestation_id);
242}
243
244}  // namespace security
245}  // namespace android
246