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 <private/android_filesystem_config.h> /* for AID_SYSTEM */
38 
39 #include <openssl/asn1t.h>
40 #include <openssl/bn.h>
41 #include <openssl/sha.h>
42 
43 #include <utils/String8.h>
44 
45 namespace android {
46 
47 namespace {
48 
49 constexpr const char* kAttestationSystemPackageName = "AndroidSystem";
50 
signature2SHA256(const content::pm::Signature & sig)51 std::vector<uint8_t> signature2SHA256(const content::pm::Signature& sig) {
52     std::vector<uint8_t> digest_buffer(SHA256_DIGEST_LENGTH);
53     SHA256(sig.data().data(), sig.data().size(), digest_buffer.data());
54     return digest_buffer;
55 }
56 
57 using ::android::security::keymaster::BpKeyAttestationApplicationIdProvider;
58 
59 class KeyAttestationApplicationIdProvider : public BpKeyAttestationApplicationIdProvider {
60   public:
61     KeyAttestationApplicationIdProvider();
62 
63     static KeyAttestationApplicationIdProvider& get();
64 
65   private:
66     android::sp<android::IServiceManager> service_manager_;
67 };
68 
get()69 KeyAttestationApplicationIdProvider& KeyAttestationApplicationIdProvider::get() {
70     static KeyAttestationApplicationIdProvider mpm;
71     return mpm;
72 }
73 
KeyAttestationApplicationIdProvider()74 KeyAttestationApplicationIdProvider::KeyAttestationApplicationIdProvider()
75     : BpKeyAttestationApplicationIdProvider(
76           android::defaultServiceManager()->getService(String16("sec_key_att_app_id_provider"))) {}
77 
78 DECLARE_STACK_OF(ASN1_OCTET_STRING);
79 
80 typedef struct km_attestation_package_info {
81     ASN1_OCTET_STRING* package_name;
82     ASN1_INTEGER* version;
83 } KM_ATTESTATION_PACKAGE_INFO;
84 
85 ASN1_SEQUENCE(KM_ATTESTATION_PACKAGE_INFO) = {
86     ASN1_SIMPLE(KM_ATTESTATION_PACKAGE_INFO, package_name, ASN1_OCTET_STRING),
87     ASN1_SIMPLE(KM_ATTESTATION_PACKAGE_INFO, version, ASN1_INTEGER),
88 } ASN1_SEQUENCE_END(KM_ATTESTATION_PACKAGE_INFO);
89 IMPLEMENT_ASN1_FUNCTIONS(KM_ATTESTATION_PACKAGE_INFO);
90 
91 DECLARE_STACK_OF(KM_ATTESTATION_PACKAGE_INFO);
92 
93 typedef struct km_attestation_application_id {
94     STACK_OF(KM_ATTESTATION_PACKAGE_INFO) * package_infos;
95     STACK_OF(ASN1_OCTET_STRING) * signature_digests;
96 } KM_ATTESTATION_APPLICATION_ID;
97 
98 ASN1_SEQUENCE(KM_ATTESTATION_APPLICATION_ID) = {
99     ASN1_SET_OF(KM_ATTESTATION_APPLICATION_ID, package_infos, KM_ATTESTATION_PACKAGE_INFO),
100     ASN1_SET_OF(KM_ATTESTATION_APPLICATION_ID, signature_digests, ASN1_OCTET_STRING),
101 } ASN1_SEQUENCE_END(KM_ATTESTATION_APPLICATION_ID);
102 IMPLEMENT_ASN1_FUNCTIONS(KM_ATTESTATION_APPLICATION_ID);
103 
104 }  // namespace
105 
106 }  // namespace android
107 
108 namespace std {
109 template <> struct default_delete<android::KM_ATTESTATION_PACKAGE_INFO> {
operator ()std::default_delete110     void operator()(android::KM_ATTESTATION_PACKAGE_INFO* p) {
111         android::KM_ATTESTATION_PACKAGE_INFO_free(p);
112     }
113 };
114 template <> struct default_delete<ASN1_OCTET_STRING> {
operator ()std::default_delete115     void operator()(ASN1_OCTET_STRING* p) { ASN1_OCTET_STRING_free(p); }
116 };
117 template <> struct default_delete<android::KM_ATTESTATION_APPLICATION_ID> {
operator ()std::default_delete118     void operator()(android::KM_ATTESTATION_APPLICATION_ID* p) {
119         android::KM_ATTESTATION_APPLICATION_ID_free(p);
120     }
121 };
122 }  // namespace std
123 
124 namespace android {
125 namespace security {
126 namespace {
127 
128 using ::android::security::keymaster::KeyAttestationApplicationId;
129 using ::android::security::keymaster::KeyAttestationPackageInfo;
130 
build_attestation_package_info(const KeyAttestationPackageInfo & pinfo,std::unique_ptr<KM_ATTESTATION_PACKAGE_INFO> * attestation_package_info_ptr)131 status_t build_attestation_package_info(const KeyAttestationPackageInfo& pinfo,
132     std::unique_ptr<KM_ATTESTATION_PACKAGE_INFO>* attestation_package_info_ptr) {
133 
134     if (!attestation_package_info_ptr) return BAD_VALUE;
135     auto& attestation_package_info = *attestation_package_info_ptr;
136 
137     attestation_package_info.reset(KM_ATTESTATION_PACKAGE_INFO_new());
138     if (!attestation_package_info.get()) return NO_MEMORY;
139 
140     if (!pinfo.package_name()) {
141         ALOGE("Key attestation package info lacks package name");
142         return BAD_VALUE;
143     }
144 
145     std::string pkg_name(String8(*pinfo.package_name()).string());
146     if (!ASN1_OCTET_STRING_set(attestation_package_info->package_name,
147                                reinterpret_cast<const unsigned char*>(pkg_name.data()),
148                                pkg_name.size())) {
149         return UNKNOWN_ERROR;
150     }
151 
152     BIGNUM* bn_version = BN_new();
153     if (bn_version == nullptr) {
154         return NO_MEMORY;
155     }
156     if (BN_set_u64(bn_version, static_cast<uint64_t>(pinfo.version_code())) != 1) {
157         BN_free(bn_version);
158         return UNKNOWN_ERROR;
159     }
160     status_t retval = NO_ERROR;
161     if (BN_to_ASN1_INTEGER(bn_version, attestation_package_info->version) == nullptr) {
162         retval = UNKNOWN_ERROR;
163     }
164     BN_free(bn_version);
165     return retval;
166 }
167 
168 StatusOr<std::vector<uint8_t>>
build_attestation_application_id(const KeyAttestationApplicationId & key_attestation_id)169 build_attestation_application_id(const KeyAttestationApplicationId& key_attestation_id) {
170     auto attestation_id =
171         std::unique_ptr<KM_ATTESTATION_APPLICATION_ID>(KM_ATTESTATION_APPLICATION_ID_new());
172 
173     auto attestation_pinfo_stack = reinterpret_cast<_STACK*>(attestation_id->package_infos);
174 
175     if (key_attestation_id.pinfos_begin() == key_attestation_id.pinfos_end()) return BAD_VALUE;
176 
177     for (auto pinfo = key_attestation_id.pinfos_begin(); pinfo != key_attestation_id.pinfos_end();
178          ++pinfo) {
179         if (!pinfo->package_name()) {
180             ALOGE("Key attestation package info lacks package name");
181             return BAD_VALUE;
182         }
183         std::string package_name(String8(*pinfo->package_name()).string());
184         std::unique_ptr<KM_ATTESTATION_PACKAGE_INFO> attestation_package_info;
185         auto rc = build_attestation_package_info(*pinfo, &attestation_package_info);
186         if (rc != NO_ERROR) {
187             ALOGE("Building DER attestation package info failed %d", rc);
188             return rc;
189         }
190         if (!sk_push(attestation_pinfo_stack, attestation_package_info.get())) {
191             return NO_MEMORY;
192         }
193         // if push succeeded, the stack takes ownership
194         attestation_package_info.release();
195     }
196 
197     /** Apps can only share a uid iff they were signed with the same certificate(s). Because the
198      *  signature field actually holds the signing certificate, rather than a signature, we can
199      *  simply use the set of signature digests of the first package info.
200      */
201     const auto& pinfo = *key_attestation_id.pinfos_begin();
202     std::vector<std::vector<uint8_t>> signature_digests;
203 
204     for (auto sig = pinfo.sigs_begin(); sig != pinfo.sigs_end(); ++sig) {
205         signature_digests.push_back(signature2SHA256(*sig));
206     }
207 
208     auto signature_digest_stack = reinterpret_cast<_STACK*>(attestation_id->signature_digests);
209     for (auto si : signature_digests) {
210         auto asn1_item = std::unique_ptr<ASN1_OCTET_STRING>(ASN1_OCTET_STRING_new());
211         if (!asn1_item) return NO_MEMORY;
212         if (!ASN1_OCTET_STRING_set(asn1_item.get(), si.data(), si.size())) {
213             return UNKNOWN_ERROR;
214         }
215         if (!sk_push(signature_digest_stack, asn1_item.get())) {
216             return NO_MEMORY;
217         }
218         asn1_item.release();  // if push succeeded, the stack takes ownership
219     }
220 
221     int len = i2d_KM_ATTESTATION_APPLICATION_ID(attestation_id.get(), nullptr);
222     if (len < 0) return UNKNOWN_ERROR;
223 
224     std::vector<uint8_t> result(len);
225     uint8_t* p = result.data();
226     len = i2d_KM_ATTESTATION_APPLICATION_ID(attestation_id.get(), &p);
227     if (len < 0) return UNKNOWN_ERROR;
228 
229     return result;
230 }
231 
232 /* The following function are not used. They are mentioned here to silence
233  * warnings about them not being used.
234  */
235 void unused_functions_silencer() __attribute__((unused));
unused_functions_silencer()236 void unused_functions_silencer() {
237     i2d_KM_ATTESTATION_PACKAGE_INFO(nullptr, nullptr);
238     d2i_KM_ATTESTATION_APPLICATION_ID(nullptr, nullptr, 0);
239     d2i_KM_ATTESTATION_PACKAGE_INFO(nullptr, nullptr, 0);
240 }
241 
242 }  // namespace
243 
gather_attestation_application_id(uid_t uid)244 StatusOr<std::vector<uint8_t>> gather_attestation_application_id(uid_t uid) {
245     KeyAttestationApplicationId key_attestation_id;
246 
247     if (uid == AID_SYSTEM) {
248         /* Use a fixed ID for system callers */
249         auto pinfo = std::make_unique<KeyAttestationPackageInfo>(
250             String16(kAttestationSystemPackageName), 1 /* version code */,
251             std::make_shared<KeyAttestationPackageInfo::SignaturesVector>());
252         key_attestation_id = KeyAttestationApplicationId(std::move(pinfo));
253     } else {
254         /* Get the attestation application ID from package manager */
255         auto& pm = KeyAttestationApplicationIdProvider::get();
256         auto status = pm.getKeyAttestationApplicationId(uid, &key_attestation_id);
257         if (!status.isOk()) {
258             ALOGE("package manager request for key attestation ID failed with: %s %d",
259                   status.exceptionMessage().string(), status.exceptionCode());
260             return FAILED_TRANSACTION;
261         }
262     }
263 
264     /* DER encode the attestation application ID */
265     return build_attestation_application_id(key_attestation_id);
266 }
267 
268 }  // namespace security
269 }  // namespace android
270