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
17 #include <keystore/keystore_attestation_id.h>
18
19 #define LOG_TAG "keystore_att_id"
20
21 #include <log/log.h>
22
23 #include <memory>
24 #include <mutex>
25 #include <string>
26 #include <vector>
27
28 #include <binder/IServiceManager.h>
29 #include <binder/Parcel.h>
30 #include <binder/Parcelable.h>
31 #include <binder/PersistableBundle.h>
32
33 #include <aidl/android/system/keystore2/ResponseCode.h>
34 #include <android/security/keystore/BpKeyAttestationApplicationIdProvider.h>
35 #include <android/security/keystore/IKeyAttestationApplicationIdProvider.h>
36 #include <android/security/keystore/KeyAttestationApplicationId.h>
37 #include <android/security/keystore/KeyAttestationPackageInfo.h>
38 #include <android/security/keystore/Signature.h>
39
40 #include <private/android_filesystem_config.h> /* for AID_SYSTEM */
41
42 #include <openssl/asn1t.h>
43 #include <openssl/bn.h>
44 #include <openssl/sha.h>
45
46 #include <utils/String8.h>
47
48 namespace android {
49
50 namespace {
51
52 constexpr const char* kAttestationSystemPackageName = "AndroidSystem";
53 constexpr const size_t kMaxAttempts = 3;
54 constexpr const unsigned long kRetryIntervalUsecs = 500000; // sleep for 500 ms
55 constexpr const char* kProviderServiceName = "sec_key_att_app_id_provider";
56
signature2SHA256(const security::keystore::Signature & sig)57 std::vector<uint8_t> signature2SHA256(const security::keystore::Signature& sig) {
58 std::vector<uint8_t> digest_buffer(SHA256_DIGEST_LENGTH);
59 SHA256(sig.data.data(), sig.data.size(), digest_buffer.data());
60 return digest_buffer;
61 }
62
63 using ::aidl::android::system::keystore2::ResponseCode;
64 using ::android::security::keystore::BpKeyAttestationApplicationIdProvider;
65
66 [[clang::no_destroy]] std::mutex gServiceMu;
67 [[clang::no_destroy]] std::shared_ptr<BpKeyAttestationApplicationIdProvider>
68 gService; // GUARDED_BY gServiceMu
69
get_service()70 std::shared_ptr<BpKeyAttestationApplicationIdProvider> get_service() {
71 std::lock_guard<std::mutex> guard(gServiceMu);
72 if (gService.get() == nullptr) {
73 gService = std::make_shared<BpKeyAttestationApplicationIdProvider>(
74 android::defaultServiceManager()->waitForService(String16(kProviderServiceName)));
75 }
76 return gService;
77 }
78
reset_service()79 void reset_service() {
80 std::lock_guard<std::mutex> guard(gServiceMu);
81 // Drop the global reference; any thread that already has a reference can keep using it.
82 gService.reset();
83 }
84
85 DECLARE_STACK_OF(ASN1_OCTET_STRING);
86
87 typedef struct km_attestation_package_info {
88 ASN1_OCTET_STRING* package_name;
89 ASN1_INTEGER* version;
90 } KM_ATTESTATION_PACKAGE_INFO;
91
92 // Estimated size:
93 // 4 bytes for the package name + package_name length
94 // 11 bytes for the version (2 bytes header and up to 9 bytes of data).
95 constexpr size_t AAID_PKG_INFO_OVERHEAD = 15;
96 ASN1_SEQUENCE(KM_ATTESTATION_PACKAGE_INFO) = {
97 ASN1_SIMPLE(KM_ATTESTATION_PACKAGE_INFO, package_name, ASN1_OCTET_STRING),
98 ASN1_SIMPLE(KM_ATTESTATION_PACKAGE_INFO, version, ASN1_INTEGER),
99 } ASN1_SEQUENCE_END(KM_ATTESTATION_PACKAGE_INFO);
100 IMPLEMENT_ASN1_FUNCTIONS(KM_ATTESTATION_PACKAGE_INFO);
101
102 DECLARE_STACK_OF(KM_ATTESTATION_PACKAGE_INFO);
103
104 // Estimated size:
105 // See estimate above for the stack of package infos.
106 // 34 (32 + 2) bytes for each signature digest.
107 constexpr size_t AAID_SIGNATURE_SIZE = 34;
108 typedef struct km_attestation_application_id {
109 STACK_OF(KM_ATTESTATION_PACKAGE_INFO) * package_infos;
110 STACK_OF(ASN1_OCTET_STRING) * signature_digests;
111 } KM_ATTESTATION_APPLICATION_ID;
112
113 // Estimated overhead:
114 // 4 for the header of the octet string containing the fully-encoded data.
115 // 4 for the sequence header.
116 // 4 for the header of the package info set.
117 // 4 for the header of the signature set.
118 constexpr size_t AAID_GENERAL_OVERHEAD = 16;
119 ASN1_SEQUENCE(KM_ATTESTATION_APPLICATION_ID) = {
120 ASN1_SET_OF(KM_ATTESTATION_APPLICATION_ID, package_infos, KM_ATTESTATION_PACKAGE_INFO),
121 ASN1_SET_OF(KM_ATTESTATION_APPLICATION_ID, signature_digests, ASN1_OCTET_STRING),
122 } ASN1_SEQUENCE_END(KM_ATTESTATION_APPLICATION_ID);
123 IMPLEMENT_ASN1_FUNCTIONS(KM_ATTESTATION_APPLICATION_ID);
124
125 } // namespace
126
127 } // namespace android
128
129 namespace std {
130 template <> struct default_delete<android::KM_ATTESTATION_PACKAGE_INFO> {
operator ()std::default_delete131 void operator()(android::KM_ATTESTATION_PACKAGE_INFO* p) {
132 android::KM_ATTESTATION_PACKAGE_INFO_free(p);
133 }
134 };
135 template <> struct default_delete<ASN1_OCTET_STRING> {
operator ()std::default_delete136 void operator()(ASN1_OCTET_STRING* p) { ASN1_OCTET_STRING_free(p); }
137 };
138 template <> struct default_delete<android::KM_ATTESTATION_APPLICATION_ID> {
operator ()std::default_delete139 void operator()(android::KM_ATTESTATION_APPLICATION_ID* p) {
140 android::KM_ATTESTATION_APPLICATION_ID_free(p);
141 }
142 };
143 } // namespace std
144
145 namespace android {
146 namespace security {
147 namespace {
148
149 using ::android::security::keystore::KeyAttestationApplicationId;
150 using ::android::security::keystore::KeyAttestationPackageInfo;
151
build_attestation_package_info(const KeyAttestationPackageInfo & pinfo,std::unique_ptr<KM_ATTESTATION_PACKAGE_INFO> * attestation_package_info_ptr)152 status_t build_attestation_package_info(const KeyAttestationPackageInfo& pinfo,
153 std::unique_ptr<KM_ATTESTATION_PACKAGE_INFO>* attestation_package_info_ptr) {
154
155 if (!attestation_package_info_ptr) return BAD_VALUE;
156 auto& attestation_package_info = *attestation_package_info_ptr;
157
158 attestation_package_info.reset(KM_ATTESTATION_PACKAGE_INFO_new());
159 if (!attestation_package_info.get()) return NO_MEMORY;
160
161 if (!pinfo.packageName) {
162 ALOGE("Key attestation package info lacks package name");
163 return BAD_VALUE;
164 }
165
166 std::string pkg_name(String8(pinfo.packageName).c_str());
167 if (!ASN1_OCTET_STRING_set(attestation_package_info->package_name,
168 reinterpret_cast<const unsigned char*>(pkg_name.data()),
169 pkg_name.size())) {
170 return UNKNOWN_ERROR;
171 }
172
173 BIGNUM* bn_version = BN_new();
174 if (bn_version == nullptr) {
175 return NO_MEMORY;
176 }
177 if (BN_set_u64(bn_version, static_cast<uint64_t>(pinfo.versionCode)) != 1) {
178 BN_free(bn_version);
179 return UNKNOWN_ERROR;
180 }
181 status_t retval = NO_ERROR;
182 if (BN_to_ASN1_INTEGER(bn_version, attestation_package_info->version) == nullptr) {
183 retval = UNKNOWN_ERROR;
184 }
185 BN_free(bn_version);
186 return retval;
187 }
188
189 /* The following function are not used. They are mentioned here to silence
190 * warnings about them not being used.
191 */
192 void unused_functions_silencer() __attribute__((unused));
unused_functions_silencer()193 void unused_functions_silencer() {
194 i2d_KM_ATTESTATION_PACKAGE_INFO(nullptr, nullptr);
195 d2i_KM_ATTESTATION_APPLICATION_ID(nullptr, nullptr, 0);
196 d2i_KM_ATTESTATION_PACKAGE_INFO(nullptr, nullptr, 0);
197 }
198
199 } // namespace
200
201 StatusOr<std::vector<uint8_t>>
build_attestation_application_id(const KeyAttestationApplicationId & key_attestation_id)202 build_attestation_application_id(const KeyAttestationApplicationId& key_attestation_id) {
203 auto attestation_id =
204 std::unique_ptr<KM_ATTESTATION_APPLICATION_ID>(KM_ATTESTATION_APPLICATION_ID_new());
205 size_t estimated_encoded_size = AAID_GENERAL_OVERHEAD;
206
207 auto attestation_pinfo_stack = reinterpret_cast<_STACK*>(attestation_id->package_infos);
208
209 if (key_attestation_id.packageInfos.begin() == key_attestation_id.packageInfos.end())
210 return BAD_VALUE;
211
212 for (auto pinfo = key_attestation_id.packageInfos.begin();
213 pinfo != key_attestation_id.packageInfos.end(); ++pinfo) {
214 if (!pinfo->packageName) {
215 ALOGE("Key attestation package info lacks package name");
216 return BAD_VALUE;
217 }
218 std::string package_name(String8(pinfo->packageName).c_str());
219 std::unique_ptr<KM_ATTESTATION_PACKAGE_INFO> attestation_package_info;
220 auto rc = build_attestation_package_info(*pinfo, &attestation_package_info);
221 if (rc != NO_ERROR) {
222 ALOGE("Building DER attestation package info failed %d", rc);
223 return rc;
224 }
225 estimated_encoded_size += AAID_PKG_INFO_OVERHEAD + package_name.size();
226 if (estimated_encoded_size > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
227 break;
228 }
229 if (!sk_push(attestation_pinfo_stack, attestation_package_info.get())) {
230 return NO_MEMORY;
231 }
232 // if push succeeded, the stack takes ownership
233 attestation_package_info.release();
234 }
235
236 /** Apps can only share a uid iff they were signed with the same certificate(s). Because the
237 * signature field actually holds the signing certificate, rather than a signature, we can
238 * simply use the set of signature digests of the first package info.
239 */
240 const auto& pinfo = *key_attestation_id.packageInfos.begin();
241 std::vector<std::vector<uint8_t>> signature_digests;
242
243 for (auto sig = pinfo.signatures.begin(); sig != pinfo.signatures.end(); ++sig) {
244 signature_digests.push_back(signature2SHA256(*sig));
245 }
246
247 auto signature_digest_stack = reinterpret_cast<_STACK*>(attestation_id->signature_digests);
248 for (auto si : signature_digests) {
249 estimated_encoded_size += AAID_SIGNATURE_SIZE;
250 if (estimated_encoded_size > KEY_ATTESTATION_APPLICATION_ID_MAX_SIZE) {
251 break;
252 }
253 auto asn1_item = std::unique_ptr<ASN1_OCTET_STRING>(ASN1_OCTET_STRING_new());
254 if (!asn1_item) return NO_MEMORY;
255 if (!ASN1_OCTET_STRING_set(asn1_item.get(), si.data(), si.size())) {
256 return UNKNOWN_ERROR;
257 }
258 if (!sk_push(signature_digest_stack, asn1_item.get())) {
259 return NO_MEMORY;
260 }
261 asn1_item.release(); // if push succeeded, the stack takes ownership
262 }
263
264 int len = i2d_KM_ATTESTATION_APPLICATION_ID(attestation_id.get(), nullptr);
265 if (len < 0) return UNKNOWN_ERROR;
266
267 std::vector<uint8_t> result(len);
268 uint8_t* p = result.data();
269 len = i2d_KM_ATTESTATION_APPLICATION_ID(attestation_id.get(), &p);
270 if (len < 0) return UNKNOWN_ERROR;
271
272 return result;
273 }
274
gather_attestation_application_id(uid_t uid)275 StatusOr<std::vector<uint8_t>> gather_attestation_application_id(uid_t uid) {
276 KeyAttestationApplicationId key_attestation_id;
277
278 if (uid == AID_SYSTEM || uid == AID_ROOT) {
279 /* Use a fixed ID for system callers */
280 auto pinfo = KeyAttestationPackageInfo();
281 pinfo.packageName = String16(kAttestationSystemPackageName);
282 pinfo.versionCode = 1;
283 key_attestation_id.packageInfos.push_back(std::move(pinfo));
284 } else {
285 /* Get the attestation application ID from package manager */
286 ::android::binder::Status status;
287
288 // Retry on failure.
289 for (size_t attempt{0}; attempt < kMaxAttempts; ++attempt) {
290 auto pm = get_service();
291 status = pm->getKeyAttestationApplicationId(uid, &key_attestation_id);
292 if (status.isOk()) {
293 break;
294 }
295
296 if (status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC) {
297 ALOGW("Retry: get attestation ID for %d failed with service specific error: %s %d",
298 uid, status.exceptionMessage().c_str(), status.serviceSpecificErrorCode());
299 } else if (status.exceptionCode() == binder::Status::EX_TRANSACTION_FAILED) {
300 // If the transaction failed, drop the package manager connection so that the next
301 // attempt will try again.
302 ALOGW(
303 "Retry: get attestation ID for %d transaction failed, reset connection: %s %d",
304 uid, status.exceptionMessage().c_str(), status.exceptionCode());
305 reset_service();
306 } else {
307 ALOGW("Retry: get attestation ID for %d failed with error: %s %d", uid,
308 status.exceptionMessage().c_str(), status.exceptionCode());
309 }
310 usleep(kRetryIntervalUsecs);
311 }
312
313 if (!status.isOk()) {
314 ALOGW("package manager request for key attestation ID failed with: %s %d",
315 status.exceptionMessage().c_str(), status.exceptionCode());
316
317 return int32_t(ResponseCode::GET_ATTESTATION_APPLICATION_ID_FAILED);
318 }
319 }
320
321 /* DER encode the attestation application ID */
322 return build_attestation_application_id(key_attestation_id);
323 }
324
325 } // namespace security
326 } // namespace android
327