1 /*
2 **
3 ** Copyright 2017, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 ** http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17
18 #include <keymaster/km_openssl/attestation_utils.h>
19
20 #include <hardware/keymaster_defs.h>
21
22 #include <keymaster/authorization_set.h>
23 #include <keymaster/attestation_record.h>
24 #include <keymaster/km_openssl/asymmetric_key.h>
25 #include <keymaster/km_openssl/openssl_utils.h>
26 #include <keymaster/km_openssl/openssl_err.h>
27
28 #include <openssl/x509v3.h>
29 #include <openssl/evp.h>
30
31
32 namespace keymaster {
33
34 namespace {
35
36 constexpr int kDigitalSignatureKeyUsageBit = 0;
37 constexpr int kKeyEnciphermentKeyUsageBit = 2;
38 constexpr int kDataEnciphermentKeyUsageBit = 3;
39 constexpr int kMaxKeyUsageBit = 8;
40
min(T && a,T && b)41 template <typename T> T && min(T && a, T && b) {
42 return (a < b) ? forward<T>(a) : forward<T>(b);
43 }
44
45 struct emptyCert {};
46
47 __attribute__((__unused__))
certBlobifier(const emptyCert &,bool *)48 inline keymaster_blob_t certBlobifier(const emptyCert&, bool*){ return {}; }
49 template <size_t N>
certBlobifier(const uint8_t (& cert)[N],bool * fail)50 inline keymaster_blob_t certBlobifier(const uint8_t (&cert)[N], bool* fail){
51 keymaster_blob_t result = { dup_array(cert), N };
52 if (!result.data) {
53 *fail = true;
54 return {};
55 }
56 return result;
57 }
certBlobifier(const keymaster_blob_t & blob,bool * fail)58 inline keymaster_blob_t certBlobifier(const keymaster_blob_t& blob, bool* fail){
59 if (blob.data == nullptr || blob.data_length == 0) return {};
60 keymaster_blob_t result = { dup_array(blob.data, blob.data_length), blob.data_length };
61 if (!result.data) {
62 *fail = true;
63 return {};
64 }
65 return result;
66 }
certBlobifier(keymaster_blob_t && blob,bool *)67 inline keymaster_blob_t certBlobifier(keymaster_blob_t&& blob, bool*){
68 if (blob.data == nullptr || blob.data_length == 0) return {};
69 keymaster_blob_t result = blob;
70 blob = {};
71 return result;
72 }
certBlobifier(X509 * certificate,bool * fail)73 inline keymaster_blob_t certBlobifier(X509* certificate, bool* fail){
74 int len = i2d_X509(certificate, nullptr);
75 if (len < 0) {
76 *fail = true;
77 return {};
78 }
79
80 uint8_t* data = new(std::nothrow) uint8_t[len];
81 if (!data) {
82 *fail = true;
83 return {};
84 }
85 uint8_t* p = data;
86
87 i2d_X509(certificate, &p);
88
89 return { data, (size_t)len };
90 }
91
certCopier(keymaster_blob_t ** out,const keymaster_cert_chain_t & chain,bool * fail)92 inline bool certCopier(keymaster_blob_t** out, const keymaster_cert_chain_t& chain,
93 bool* fail) {
94 for (size_t i = 0; i < chain.entry_count; ++i) {
95 *(*out)++ = certBlobifier(chain.entries[i], fail);
96 }
97 return *fail;
98 }
99
100 __attribute__((__unused__))
certCopier(keymaster_blob_t ** out,keymaster_cert_chain_t && chain,bool * fail)101 inline bool certCopier(keymaster_blob_t** out, keymaster_cert_chain_t&& chain, bool* fail) {
102 for (size_t i = 0; i < chain.entry_count; ++i) {
103 *(*out)++ = certBlobifier(move(chain.entries[i]), fail);
104 }
105 delete[] chain.entries;
106 chain.entries = nullptr;
107 chain.entry_count = 0;
108 return *fail;
109 }
110 template <typename CERT>
certCopier(keymaster_blob_t ** out,CERT && cert,bool * fail)111 inline bool certCopier(keymaster_blob_t** out, CERT&& cert, bool* fail) {
112 *(*out)++ = certBlobifier(forward<CERT>(cert), fail);
113 return *fail;
114 }
115
certCopyHelper(keymaster_blob_t **,bool * fail)116 inline bool certCopyHelper(keymaster_blob_t**, bool* fail) {
117 return *fail;
118 }
119
120 template <typename CERT, typename... CERTS>
certCopyHelper(keymaster_blob_t ** out,bool * fail,CERT && cert,CERTS &&...certs)121 inline bool certCopyHelper(keymaster_blob_t** out, bool* fail, CERT&& cert, CERTS&&... certs) {
122 certCopier(out, forward<CERT>(cert), fail);
123 return certCopyHelper(out, fail, forward<CERTS>(certs)...);
124 }
125
126
127
128 template <typename T>
noOfCert(T &&)129 inline size_t noOfCert(T &&) { return 1; }
noOfCert(const keymaster_cert_chain_t & cert_chain)130 inline size_t noOfCert(const keymaster_cert_chain_t& cert_chain) { return cert_chain.entry_count; }
131
certCount()132 inline size_t certCount() { return 0; }
133 template <typename CERT, typename... CERTS>
certCount(CERT && cert,CERTS &&...certs)134 inline size_t certCount(CERT&& cert, CERTS&&... certs) {
135 return noOfCert(forward<CERT>(cert)) + certCount(forward<CERTS>(certs)...);
136 }
137
138 /*
139 * makeCertChain creates a new keymaster_cert_chain_t from all the certs that get thrown at it
140 * in the given order. A cert may be a X509*, uint8_t[], a keymaster_blob_t, an instance of
141 * emptyCert, or another keymater_cert_chain_t in which case the certs of the chain are included
142 * in the new chain. emptyCert is a placeholder which results in an empty slot at the given
143 * position in the newly created certificate chain. E.g., makeCertChain(emptyCert(), someCertChain)
144 * allocates enough slots to accommodate all certificates of someCertChain plus one empty slot and
145 * copies in someCertChain starting at index 1 so that the slot with index 0 can be used for a new
146 * leaf entry.
147 *
148 * makeCertChain respects move semantics. E.g., makeCertChain(emptyCert(), std::move(someCertChain))
149 * will take possession of secondary resources for the certificate blobs so that someCertChain is
150 * empty after the call. Also, because no allocation happens this cannot fail. Note, however, that
151 * if another cert is passed to makeCertChain, that needs to be copied and thus requires
152 * allocation, and this allocation fails, all resources - allocated or moved - will be reaped.
153 */
154 template <typename... CERTS>
makeCertChain(CERTS &&...certs)155 CertChainPtr makeCertChain(CERTS&&... certs) {
156 CertChainPtr result(new (std::nothrow) keymaster_cert_chain_t);
157 if (!result.get()) return {};
158 result->entries = new (std::nothrow) keymaster_blob_t[certCount(forward<CERTS>(certs)...)];
159 if (!result->entries) return {};
160 result->entry_count = certCount(forward<CERTS>(certs)...);
161 bool allocation_failed = false;
162 keymaster_blob_t* entries = result->entries;
163 certCopyHelper(&entries, &allocation_failed, forward<CERTS>(certs)...);
164 if (allocation_failed) return {};
165 return result;
166 }
167
168
build_attestation_extension(const AuthorizationSet & attest_params,const AuthorizationSet & tee_enforced,const AuthorizationSet & sw_enforced,const AttestationRecordContext & context,X509_EXTENSION_Ptr * extension)169 keymaster_error_t build_attestation_extension(const AuthorizationSet& attest_params,
170 const AuthorizationSet& tee_enforced,
171 const AuthorizationSet& sw_enforced,
172 const AttestationRecordContext& context,
173 X509_EXTENSION_Ptr* extension) {
174 ASN1_OBJECT_Ptr oid(
175 OBJ_txt2obj(kAttestionRecordOid, 1 /* accept numerical dotted string form only */));
176 if (!oid.get())
177 return TranslateLastOpenSslError();
178
179 UniquePtr<uint8_t[]> attest_bytes;
180 size_t attest_bytes_len;
181 keymaster_error_t error = build_attestation_record(attest_params, sw_enforced, tee_enforced,
182 context, &attest_bytes, &attest_bytes_len);
183 if (error != KM_ERROR_OK)
184 return error;
185
186 ASN1_OCTET_STRING_Ptr attest_str(ASN1_OCTET_STRING_new());
187 if (!attest_str.get() ||
188 !ASN1_OCTET_STRING_set(attest_str.get(), attest_bytes.get(), attest_bytes_len))
189 return TranslateLastOpenSslError();
190
191 extension->reset(
192 X509_EXTENSION_create_by_OBJ(nullptr, oid.get(), 0 /* not critical */, attest_str.get()));
193 if (!extension->get())
194 return TranslateLastOpenSslError();
195
196 return KM_ERROR_OK;
197 }
198
add_key_usage_extension(const AuthorizationSet & tee_enforced,const AuthorizationSet & sw_enforced,X509 * certificate)199 keymaster_error_t add_key_usage_extension(const AuthorizationSet& tee_enforced,
200 const AuthorizationSet& sw_enforced,
201 X509* certificate) {
202 // Build BIT_STRING with correct contents.
203 ASN1_BIT_STRING_Ptr key_usage(ASN1_BIT_STRING_new());
204 if (!key_usage) return KM_ERROR_MEMORY_ALLOCATION_FAILED;
205
206 for (size_t i = 0; i <= kMaxKeyUsageBit; ++i) {
207 if (!ASN1_BIT_STRING_set_bit(key_usage.get(), i, 0)) {
208 return TranslateLastOpenSslError();
209 }
210 }
211
212 if (tee_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_SIGN) ||
213 tee_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_VERIFY) ||
214 sw_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_SIGN) ||
215 sw_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_VERIFY)) {
216 if (!ASN1_BIT_STRING_set_bit(key_usage.get(), kDigitalSignatureKeyUsageBit, 1)) {
217 return TranslateLastOpenSslError();
218 }
219 }
220
221 if (tee_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_ENCRYPT) ||
222 tee_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_DECRYPT) ||
223 sw_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_ENCRYPT) ||
224 sw_enforced.Contains(TAG_PURPOSE, KM_PURPOSE_DECRYPT)) {
225 if (!ASN1_BIT_STRING_set_bit(key_usage.get(), kKeyEnciphermentKeyUsageBit, 1) ||
226 !ASN1_BIT_STRING_set_bit(key_usage.get(), kDataEnciphermentKeyUsageBit, 1)) {
227 return TranslateLastOpenSslError();
228 }
229 }
230
231 // Convert to octets
232 int len = i2d_ASN1_BIT_STRING(key_usage.get(), nullptr);
233 if (len < 0) {
234 return TranslateLastOpenSslError();
235 }
236 UniquePtr<uint8_t[]> asn1_key_usage(new(std::nothrow) uint8_t[len]);
237 if (!asn1_key_usage.get()) {
238 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
239 }
240 uint8_t* p = asn1_key_usage.get();
241 len = i2d_ASN1_BIT_STRING(key_usage.get(), &p);
242 if (len < 0) {
243 return TranslateLastOpenSslError();
244 }
245
246 // Build OCTET_STRING
247 ASN1_OCTET_STRING_Ptr key_usage_str(ASN1_OCTET_STRING_new());
248 if (!key_usage_str.get() ||
249 !ASN1_OCTET_STRING_set(key_usage_str.get(), asn1_key_usage.get(), len)) {
250 return TranslateLastOpenSslError();
251 }
252
253 X509_EXTENSION_Ptr key_usage_extension(X509_EXTENSION_create_by_NID(nullptr, //
254 NID_key_usage, //
255 false /* critical */,
256 key_usage_str.get()));
257 if (!key_usage_extension.get()) {
258 return TranslateLastOpenSslError();
259 }
260
261 if (!X509_add_ext(certificate, key_usage_extension.get() /* Don't release; copied */,
262 -1 /* insert at end */)) {
263 return TranslateLastOpenSslError();
264 }
265
266 return KM_ERROR_OK;
267 }
268
add_public_key(EVP_PKEY * key,X509 * certificate,keymaster_error_t * error)269 bool add_public_key(EVP_PKEY* key, X509* certificate, keymaster_error_t* error) {
270 if (!X509_set_pubkey(certificate, key)) {
271 *error = TranslateLastOpenSslError();
272 return false;
273 }
274 return true;
275 }
276
add_attestation_extension(const AuthorizationSet & attest_params,const AuthorizationSet & tee_enforced,const AuthorizationSet & sw_enforced,const AttestationRecordContext & context,X509 * certificate,keymaster_error_t * error)277 bool add_attestation_extension(const AuthorizationSet& attest_params,
278 const AuthorizationSet& tee_enforced,
279 const AuthorizationSet& sw_enforced,
280 const AttestationRecordContext& context,
281 X509* certificate,
282 keymaster_error_t* error) {
283 X509_EXTENSION_Ptr attest_extension;
284 *error = build_attestation_extension(attest_params, tee_enforced, sw_enforced, context,
285 &attest_extension);
286 if (*error != KM_ERROR_OK)
287 return false;
288
289 if (!X509_add_ext(certificate, attest_extension.get() /* Don't release; copied */,
290 -1 /* insert at end */)) {
291 *error = TranslateLastOpenSslError();
292 return false;
293 }
294
295 return true;
296 }
297
298 } // anonymous namespace
299
generate_attestation(const AsymmetricKey & key,const AuthorizationSet & attest_params,const keymaster_cert_chain_t & attestation_chain,const keymaster_key_blob_t & attestation_signing_key,const AttestationRecordContext & context,CertChainPtr * cert_chain_out)300 keymaster_error_t generate_attestation(const AsymmetricKey& key,
301 const AuthorizationSet& attest_params, const keymaster_cert_chain_t& attestation_chain,
302 const keymaster_key_blob_t& attestation_signing_key,
303 const AttestationRecordContext& context, CertChainPtr* cert_chain_out) {
304
305 if (!cert_chain_out)
306 return KM_ERROR_UNEXPECTED_NULL_POINTER;
307
308 keymaster_algorithm_t sign_algorithm;
309 if ((!key.sw_enforced().GetTagValue(TAG_ALGORITHM, &sign_algorithm) &&
310 !key.hw_enforced().GetTagValue(TAG_ALGORITHM, &sign_algorithm)))
311 return KM_ERROR_UNKNOWN_ERROR;
312
313 EVP_PKEY_Ptr pkey(EVP_PKEY_new());
314 if (!key.InternalToEvp(pkey.get()))
315 return TranslateLastOpenSslError();
316
317 X509_Ptr certificate(X509_new());
318 if (!certificate.get())
319 return TranslateLastOpenSslError();
320
321 if (!X509_set_version(certificate.get(), 2 /* version 3, but zero-based */))
322 return TranslateLastOpenSslError();
323
324 ASN1_INTEGER_Ptr serialNumber(ASN1_INTEGER_new());
325 if (!serialNumber.get() || !ASN1_INTEGER_set(serialNumber.get(), 1) ||
326 !X509_set_serialNumber(certificate.get(), serialNumber.get() /* Don't release; copied */))
327 return TranslateLastOpenSslError();
328
329 X509_NAME_Ptr subjectName(X509_NAME_new());
330 if (!subjectName.get() ||
331 !X509_NAME_add_entry_by_txt(subjectName.get(), "CN", MBSTRING_ASC,
332 reinterpret_cast<const uint8_t*>("Android Keystore Key"),
333 -1 /* len */, -1 /* loc */, 0 /* set */) ||
334 !X509_set_subject_name(certificate.get(), subjectName.get() /* Don't release; copied */))
335 return TranslateLastOpenSslError();
336
337 ASN1_TIME_Ptr notBefore(ASN1_TIME_new());
338 uint64_t activeDateTime = 0;
339 key.authorizations().GetTagValue(TAG_ACTIVE_DATETIME, &activeDateTime);
340 if (!notBefore.get() || !ASN1_TIME_set(notBefore.get(), activeDateTime / 1000) ||
341 !X509_set_notBefore(certificate.get(), notBefore.get() /* Don't release; copied */))
342 return TranslateLastOpenSslError();
343
344 ASN1_TIME_Ptr notAfter(ASN1_TIME_new());
345 uint64_t usageExpireDateTime = UINT64_MAX;
346 key.authorizations().GetTagValue(TAG_USAGE_EXPIRE_DATETIME, &usageExpireDateTime);
347 // TODO(swillden): When trusty can use the C++ standard library change the calculation of
348 // notAfterTime to use std::numeric_limits<time_t>::max(), rather than assuming that time_t is
349 // 32 bits.
350 time_t notAfterTime = min(static_cast<uint64_t>(UINT32_MAX), usageExpireDateTime / 1000);
351 if (!notAfter.get() || !ASN1_TIME_set(notAfter.get(), notAfterTime) ||
352 !X509_set_notAfter(certificate.get(), notAfter.get() /* Don't release; copied */))
353 return TranslateLastOpenSslError();
354
355 keymaster_error_t error = add_key_usage_extension(key.hw_enforced(), key.sw_enforced(), certificate.get());
356 if (error != KM_ERROR_OK) {
357 return error;
358 }
359
360 // We have established above that it is one of the two. So if it is not RSA its EC.
361 int evp_key_type = (sign_algorithm == KM_ALGORITHM_RSA) ? EVP_PKEY_RSA : EVP_PKEY_EC;
362
363 const uint8_t* key_material = attestation_signing_key.key_material;
364 EVP_PKEY_Ptr sign_key(
365 d2i_PrivateKey(evp_key_type, nullptr,
366 const_cast<const uint8_t**>(&key_material),
367 attestation_signing_key.key_material_size));
368 if (!sign_key.get()) return TranslateLastOpenSslError();
369
370 if (!add_public_key(pkey.get(), certificate.get(), &error) ||
371 !add_attestation_extension(attest_params, key.hw_enforced(), key.sw_enforced(),
372 context, certificate.get(), &error))
373 return error;
374
375 if (attestation_chain.entry_count < 1) {
376 // the attestation chain must have at least the cert for the key that signs the new cert.
377 return KM_ERROR_UNKNOWN_ERROR;
378 }
379
380 const uint8_t* p = attestation_chain.entries[0].data;
381 X509_Ptr signing_cert(d2i_X509(nullptr, &p, attestation_chain.entries[0].data_length));
382 if (!signing_cert.get()) {
383 return TranslateLastOpenSslError();
384 }
385
386 // Set issuer to subject of batch certificate.
387 X509_NAME* issuerSubject = X509_get_subject_name(signing_cert.get());
388 if (!issuerSubject) {
389 return KM_ERROR_UNKNOWN_ERROR;
390 }
391 if (!X509_set_issuer_name(certificate.get(), issuerSubject)) {
392 return TranslateLastOpenSslError();
393 }
394
395 UniquePtr<X509V3_CTX> x509v3_ctx(new(std::nothrow) X509V3_CTX);
396 if (!x509v3_ctx.get())
397 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
398 *x509v3_ctx = {};
399 X509V3_set_ctx(x509v3_ctx.get(), signing_cert.get(), certificate.get(), nullptr /* req */,
400 nullptr /* crl */, 0 /* flags */);
401
402 X509_EXTENSION_Ptr auth_key_id(X509V3_EXT_nconf_nid(nullptr /* conf */, x509v3_ctx.get(),
403 NID_authority_key_identifier,
404 const_cast<char*>("keyid:always")));
405 if (!auth_key_id.get() ||
406 !X509_add_ext(certificate.get(), auth_key_id.get() /* Don't release; copied */,
407 -1 /* insert at end */)) {
408 return TranslateLastOpenSslError();
409 }
410
411 if (!X509_sign(certificate.get(), sign_key.get(), EVP_sha256()))
412 return TranslateLastOpenSslError();
413
414 *cert_chain_out = makeCertChain(certificate.get(), attestation_chain);
415 if (!cert_chain_out->get())
416 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
417 return KM_ERROR_OK;
418 }
419
420
421 } // namespace keymaster
422