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 #define TLOG_TAG "hwkey_fake_srv"
18 
19 #include <assert.h>
20 #include <lk/compiler.h>
21 #include <stdbool.h>
22 #include <stddef.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <uapi/err.h>
27 
28 #include <openssl/aes.h>
29 #include <openssl/cipher.h>
30 #include <openssl/digest.h>
31 #include <openssl/err.h>
32 #include <openssl/hkdf.h>
33 
34 #include <interface/hwaes/hwaes.h>
35 #include <interface/hwkey/hwkey.h>
36 #include <lib/system_state/system_state.h>
37 #include <lib/tipc/tipc.h>
38 #include <lib/tipc/tipc_srv.h>
39 #include <trusty_log.h>
40 
41 #include <hwcrypto_consts.h>
42 #include "hwkey_srv_priv.h"
43 
44 #pragma message "Compiling FAKE HWKEY provider"
45 
46 /* 0 means unlimited number of connections */
47 #define HWKEY_MAX_NUM_CHANNELS 0
48 
49 /*
50  *  This module is a sample only. For real device, this code
51  *  needs to be rewritten to operate on real per device key that
52  *  should come directly or indirectly from hardware.
53  */
54 static uint8_t fake_device_key[32] = "this is a fake unique device key";
55 static uint8_t fake_shared_key[32] = "this is a fake shared device key";
56 
57 /*
58  * Fake rollback versions for testing the sample app. These versions should be
59  * pulled from a secure source of truth in a real implementation.
60  */
61 #define FAKE_TRUSTY_RUNNING_ROLLBACK_VERSION 2
62 #define FAKE_TRUSTY_COMMITTED_ROLLBACK_VERSION 1
63 
64 /* This input vector is taken from RFC 5869 (Extract-and-Expand HKDF) */
65 static const uint8_t IKM[] = {0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
66                               0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
67                               0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b};
68 
69 static const uint8_t salt[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
70                                0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c};
71 
72 static const uint8_t info[] = {0xf0, 0xf1, 0xf2, 0xf3, 0xf4,
73                                0xf5, 0xf6, 0xf7, 0xf8, 0xf9};
74 
75 /* Expected pseudorandom key */
76 /*static const uint8_t exp_PRK[] = { 0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32,
77    0xdf, 0x0d, 0xdc, 0x3f, 0x0d, 0xc4, 0x7b, 0xba, 0x63, 0x90, 0xb6, 0xc7, 0x3b,
78    0xb5, 0x0f, 0x9c, 0x31, 0x22, 0xec, 0x84, 0x4a, 0xd7, 0xc2, 0xb3, 0xe5 };*/
79 
80 /* Expected Output Key */
81 static const uint8_t exp_OKM[42] = {
82         0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 0x4f,
83         0x64, 0xd0, 0x36, 0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a,
84         0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4, 0xc5, 0xbf, 0x34,
85         0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65};
86 
hkdf_self_test(void)87 static bool hkdf_self_test(void) {
88     int res;
89     uint8_t OKM[sizeof(exp_OKM)];
90 
91     TLOGI("hkdf self test\n");
92 
93     /* Check if OKM is OK */
94     memset(OKM, 0x55, sizeof(OKM));
95 
96     res = HKDF(OKM, sizeof(OKM), EVP_sha256(), IKM, sizeof(IKM), salt,
97                sizeof(salt), info, sizeof(info));
98     if (!res) {
99         TLOGE("hkdf: failed 0x%x\n", ERR_get_error());
100         return false;
101     }
102 
103     res = memcmp(OKM, exp_OKM, sizeof(OKM));
104     if (res) {
105         TLOGE("hkdf: data mismatch\n");
106         return false;
107     }
108 
109     TLOGI("hkdf self test: PASSED\n");
110     return true;
111 }
112 
113 /*
114  * Derive key V1 - HMAC SHA256 based Key derivation function
115  */
derive_key_v1(const uuid_t * uuid,const uint8_t * ikm_data,size_t ikm_len,uint8_t * key_buf,size_t key_len)116 uint32_t derive_key_v1(const uuid_t* uuid,
117                        const uint8_t* ikm_data,
118                        size_t ikm_len,
119                        uint8_t* key_buf,
120                        size_t key_len) {
121     if (!ikm_len) {
122         return HWKEY_ERR_BAD_LEN;
123     }
124 
125     if (!HKDF(key_buf, key_len, EVP_sha256(), (const uint8_t*)fake_device_key,
126               sizeof(fake_device_key), (const uint8_t*)uuid, sizeof(uuid_t),
127               ikm_data, ikm_len)) {
128         TLOGE("HDKF failed 0x%x\n", ERR_get_error());
129         memset(key_buf, 0, key_len);
130         return HWKEY_ERR_GENERIC;
131     }
132 
133     return HWKEY_NO_ERROR;
134 }
135 
136 /*
137  * Context labels for key derivation contexts, see derive_key_versioned_v1() for
138  * details.
139  */
140 #define HWKEY_DERIVE_VERSIONED_CONTEXT_LABEL "DERIVE VERSIONED"
141 #define ROOT_OF_TRUST_DERIVE_CONTEXT_LABEL "TZOS"
142 
143 #define HWKEY_DERIVE_VERSIONED_SALT "hwkey derive versioned salt"
144 
145 static uint8_t context_buf[4096];
146 
147 /**
148  * fill_context_buf() - Add data to context_buf
149  * @src: Pointer to data to copy into the context buf. If null, @len zero bytes
150  *       will be added.
151  * @len: Number of bytes of data to add.
152  * @cur_position: Pointer to the next unwritten byte of context_buf. Updated
153  *                with the new current position when successful.
154  *
155  * Return: HWKEY_NO_ERROR on success, HWKEY_ERR_BAD_LEN if @len will cause the
156  * buffer to overflow.
157  */
fill_context_buf(const void * src,size_t len,size_t * cur_position)158 static uint32_t fill_context_buf(const void* src,
159                                  size_t len,
160                                  size_t* cur_position) {
161     size_t new_position;
162     if (len == 0) {
163         return HWKEY_NO_ERROR;
164     }
165     if (__builtin_add_overflow(*cur_position, len, &new_position) ||
166         new_position >= sizeof(context_buf)) {
167         return HWKEY_ERR_BAD_LEN;
168     }
169     if (src == NULL) {
170         memset(&context_buf[*cur_position], 0, len);
171     } else {
172         memcpy(&context_buf[*cur_position], src, len);
173     }
174     *cur_position = new_position;
175     return HWKEY_NO_ERROR;
176 }
177 
178 /*
179  * In a real implementation this portion of the derivation should be done by a
180  * trusted source of the Trusty OS rollback version. Doing the key derivation
181  * here in the hwkey service protects against some app-level compromises, but
182  * does not protect against compromise of any Trusty code that can derive
183  * directly using the secret key derivation input - which in this sample
184  * implementation would be the kernel and the hwkey service.
185  *
186  * This function MUST mix @rollback_version_source, @os_rollback_version, and
187  * @hwkey_context into the derivation context in a way that the client cannot
188  * forge.
189  */
root_of_trust_derive_key(bool shared,uint32_t rollback_version_source,int32_t os_rollback_version,const uint8_t * hwkey_context,size_t hwkey_context_len,uint8_t * key_buf,size_t key_len)190 static uint32_t root_of_trust_derive_key(bool shared,
191                                          uint32_t rollback_version_source,
192                                          int32_t os_rollback_version,
193                                          const uint8_t* hwkey_context,
194                                          size_t hwkey_context_len,
195                                          uint8_t* key_buf,
196                                          size_t key_len) {
197     size_t context_len = 0;
198     int rc;
199     const size_t root_of_trust_context_len =
200             sizeof(ROOT_OF_TRUST_DERIVE_CONTEXT_LABEL) +
201             sizeof(rollback_version_source) + sizeof(os_rollback_version);
202     const uint8_t* secret_key;
203     size_t secret_key_len;
204     size_t total_len;
205 
206     /*
207      * We need to move the hwkey_context (currently at the beginning of
208      * context_buf) over to make room for the root-of-trust context injected
209      * before it. We avoid the need for a separate buffer by memmoving it first
210      * then adding the context into the space we made.
211      */
212     if (__builtin_add_overflow(hwkey_context_len, root_of_trust_context_len,
213                                &total_len) ||
214         total_len >= sizeof(context_buf)) {
215         return HWKEY_ERR_BAD_LEN;
216     }
217     memmove(&context_buf[root_of_trust_context_len], hwkey_context,
218             hwkey_context_len);
219 
220     /*
221      * Add a fixed label to ensure that another user of the same key derivation
222      * primitive will not collide with this use, regardless of the provided
223      * hwkey_context (as long as other users also add a different fixed label).
224      */
225     rc = fill_context_buf(ROOT_OF_TRUST_DERIVE_CONTEXT_LABEL,
226                           sizeof(ROOT_OF_TRUST_DERIVE_CONTEXT_LABEL),
227                           &context_len);
228     if (rc) {
229         return rc;
230     }
231     /* Keys for different version limit sources must be different */
232     rc = fill_context_buf(&rollback_version_source,
233                           sizeof(rollback_version_source), &context_len);
234     if (rc) {
235         return rc;
236     }
237     /*
238      * Keys with different rollback versions must not be the same. This is part
239      * of the root-of-trust context to ensure that a compromised kernel cannot
240      * forge a version (if the root of trust is outside of Trusty)
241      */
242     rc = fill_context_buf(&os_rollback_version, sizeof(os_rollback_version),
243                           &context_len);
244     if (rc) {
245         return rc;
246     }
247 
248     assert(root_of_trust_context_len == context_len);
249 
250     /*
251      * We already moved the hwkey_context into place after the root of trust
252      * context.
253      */
254     context_len += hwkey_context_len;
255 
256     if (shared) {
257         secret_key = fake_shared_key;
258         secret_key_len = sizeof(fake_shared_key);
259     } else {
260         secret_key = fake_device_key;
261         secret_key_len = sizeof(fake_device_key);
262     }
263 
264     if (!HKDF(key_buf, key_len, EVP_sha256(), secret_key, secret_key_len,
265               (const uint8_t*)HWKEY_DERIVE_VERSIONED_SALT,
266               sizeof(HWKEY_DERIVE_VERSIONED_SALT), context_buf, context_len)) {
267         TLOGE("HDKF failed 0x%x\n", ERR_get_error());
268         memset(key_buf, 0, key_len);
269         return HWKEY_ERR_GENERIC;
270     }
271     return HWKEY_NO_ERROR;
272 }
273 
get_current_os_rollback_version(uint32_t source)274 int32_t get_current_os_rollback_version(uint32_t source) {
275     switch (source) {
276     case HWKEY_ROLLBACK_RUNNING_VERSION:
277         return FAKE_TRUSTY_RUNNING_ROLLBACK_VERSION;
278 
279     case HWKEY_ROLLBACK_COMMITTED_VERSION:
280         return FAKE_TRUSTY_COMMITTED_ROLLBACK_VERSION;
281 
282     default:
283         TLOGE("Unknown rollback version source: %u\n", source);
284         return ERR_NOT_VALID;
285     }
286 }
287 
288 /*
289  * Derive a versioned key - HMAC SHA256 based versioned key derivation function
290  */
derive_key_versioned_v1(const uuid_t * uuid,bool shared,uint32_t rollback_version_source,int32_t rollback_versions[HWKEY_ROLLBACK_VERSION_INDEX_COUNT],const uint8_t * user_context,size_t user_context_len,uint8_t * key_buf,size_t key_len)291 uint32_t derive_key_versioned_v1(
292         const uuid_t* uuid,
293         bool shared,
294         uint32_t rollback_version_source,
295         int32_t rollback_versions[HWKEY_ROLLBACK_VERSION_INDEX_COUNT],
296         const uint8_t* user_context,
297         size_t user_context_len,
298         uint8_t* key_buf,
299         size_t key_len) {
300     size_t context_len = 0;
301     int i;
302     uint32_t rc = HWKEY_NO_ERROR;
303     int32_t os_rollback_version =
304             rollback_versions[HWKEY_ROLLBACK_VERSION_OS_INDEX];
305     int32_t os_rollback_version_current =
306             get_current_os_rollback_version(rollback_version_source);
307 
308     if (os_rollback_version_current < 0) {
309         rc = HWKEY_ERR_NOT_VALID;
310         goto err;
311     }
312 
313     if (os_rollback_version > os_rollback_version_current) {
314         TLOGE("Requested rollback version too new: %u\n", os_rollback_version);
315         rc = HWKEY_ERR_NOT_FOUND;
316         goto err;
317     }
318 
319     /* short-circuit derivation if we have nothing to derive */
320     if (key_len == 0) {
321         rc = HWKEY_NO_ERROR;
322         goto err;
323     }
324 
325     /* for compatibility with unversioned derive, require a context */
326     if (!key_buf || !user_context || user_context_len == 0) {
327         rc = HWKEY_ERR_NOT_VALID;
328         goto err;
329     }
330 
331     /*
332      * This portion of the context may always be added by the hwkey service, as
333      * it deals with the identity of the client requesting the key derivation.
334      */
335     /*
336      * Fixed label ensures that this derivation will not collide with a
337      * different user of root_of_trust_derive_key(), regardless of the provided
338      * user context (as long as other users also add a different fixed label).
339      */
340     rc = fill_context_buf(HWKEY_DERIVE_VERSIONED_CONTEXT_LABEL,
341                           sizeof(HWKEY_DERIVE_VERSIONED_CONTEXT_LABEL),
342                           &context_len);
343     if (rc) {
344         goto err;
345     }
346     /* Keys for different apps must be different */
347     rc = fill_context_buf(uuid, sizeof(*uuid), &context_len);
348     if (rc) {
349         goto err;
350     }
351     for (i = 0; i < HWKEY_ROLLBACK_VERSION_SUPPORTED_COUNT; ++i) {
352         /*
353          * We skip the OS version because the root-of-trust should be inserting
354          * that, and we don't want to mask a buggy implementation there in
355          * testing. If the root-of-trust somehow did not insert the OS version,
356          * we want to notice.
357          */
358         if (i == HWKEY_ROLLBACK_VERSION_OS_INDEX) {
359             continue;
360         }
361         rc = fill_context_buf(&rollback_versions[i], sizeof(*rollback_versions),
362                               &context_len);
363         if (rc) {
364             goto err;
365         }
366     }
367     /* Reserve space for additional versions in the future */
368     if (HWKEY_ROLLBACK_VERSION_SUPPORTED_COUNT <
369         HWKEY_ROLLBACK_VERSION_INDEX_COUNT) {
370         rc = fill_context_buf(NULL,
371                               sizeof(*rollback_versions) *
372                                       (HWKEY_ROLLBACK_VERSION_INDEX_COUNT -
373                                        HWKEY_ROLLBACK_VERSION_SUPPORTED_COUNT),
374                               &context_len);
375         if (rc) {
376             goto err;
377         }
378     }
379     /*
380      * Clients need to be able to generate multiple different keys in the same
381      * app.
382      */
383     rc = fill_context_buf(user_context, user_context_len, &context_len);
384     if (rc) {
385         goto err;
386     }
387 
388     rc = root_of_trust_derive_key(shared, rollback_version_source,
389                                   os_rollback_version, context_buf, context_len,
390                                   key_buf, key_len);
391     if (rc) {
392         goto err;
393     }
394 
395 err:
396     memset(context_buf, 0, sizeof(context_buf));
397     return rc;
398 }
399 
400 /* UUID of HWCRYPTO_UNITTEST application */
401 static const uuid_t hwcrypto_unittest_uuid = HWCRYPTO_UNITTEST_APP_UUID;
402 static const uuid_t hwcrypto_unittest_rust_uuid =
403         HWCRYPTO_UNITTEST_RUST_APP_UUID;
404 
405 #if WITH_HWCRYPTO_UNITTEST
406 /*
407  *  Support for hwcrypto unittest keys should be only enabled
408  *  to test hwcrypto related APIs
409  */
410 
411 static uint8_t _unittest_key32[32] = "unittestkeyslotunittestkeyslotun";
get_unittest_key32(uint8_t * kbuf,size_t kbuf_len,size_t * klen)412 static uint32_t get_unittest_key32(uint8_t* kbuf,
413                                    size_t kbuf_len,
414                                    size_t* klen) {
415     assert(kbuf);
416     assert(klen);
417     assert(kbuf_len >= sizeof(_unittest_key32));
418 
419     /* just return predefined key */
420     memcpy(kbuf, _unittest_key32, sizeof(_unittest_key32));
421     *klen = sizeof(_unittest_key32);
422 
423     return HWKEY_NO_ERROR;
424 }
425 
get_unittest_key32_handler(const struct hwkey_keyslot * slot,uint8_t * kbuf,size_t kbuf_len,size_t * klen)426 static uint32_t get_unittest_key32_handler(const struct hwkey_keyslot* slot,
427                                            uint8_t* kbuf,
428                                            size_t kbuf_len,
429                                            size_t* klen) {
430     return get_unittest_key32(kbuf, kbuf_len, klen);
431 }
432 
433 /*
434  * "unittestderivedkeyslotunittestde" encrypted with _unittest_key32 using an
435  * all 0 IV. IV is prepended to the ciphertext.
436  */
437 static uint8_t _unittest_encrypted_key32[48] = {
438         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
439         0x00, 0x00, 0x00, 0x00, 0x3e, 0x2b, 0x02, 0x54, 0x54, 0x8c, 0xa7, 0xb8,
440         0xa3, 0xfa, 0xf5, 0xd0, 0xbc, 0x1d, 0x40, 0x11, 0xac, 0x68, 0xbb, 0xf0,
441         0x55, 0xa3, 0xc5, 0x49, 0x3e, 0x77, 0x4a, 0x8b, 0x3f, 0x33, 0x56, 0x07,
442 };
443 
444 static unsigned int _unittest_encrypted_key32_size =
445         sizeof(_unittest_encrypted_key32);
446 
get_unittest_key32_derived(const struct hwkey_derived_keyslot_data * data,uint8_t * kbuf,size_t kbuf_len,size_t * klen)447 static uint32_t get_unittest_key32_derived(
448         const struct hwkey_derived_keyslot_data* data,
449         uint8_t* kbuf,
450         size_t kbuf_len,
451         size_t* klen) {
452     return get_unittest_key32(kbuf, kbuf_len, klen);
453 }
454 
455 static const struct hwkey_derived_keyslot_data hwcrypto_unittest_derived_data =
456         {
457                 .encrypted_key_data = _unittest_encrypted_key32,
458                 .encrypted_key_size_ptr = &_unittest_encrypted_key32_size,
459                 .retriever = get_unittest_key32_derived,
460 };
461 
derived_keyslot_handler(const struct hwkey_keyslot * slot,uint8_t * kbuf,size_t kbuf_len,size_t * klen)462 static uint32_t derived_keyslot_handler(const struct hwkey_keyslot* slot,
463                                         uint8_t* kbuf,
464                                         size_t kbuf_len,
465                                         size_t* klen) {
466     assert(slot);
467     return hwkey_get_derived_key(slot->priv, kbuf, kbuf_len, klen);
468 }
469 
470 static const uuid_t* unittest_allowed_opaque_key_uuids[] = {
471         &hwcrypto_unittest_uuid,
472         &hwcrypto_unittest_rust_uuid,
473 };
474 
get_unittest_key32_opaque(const struct hwkey_opaque_handle_data * data,uint8_t * kbuf,size_t kbuf_len,size_t * klen)475 static uint32_t get_unittest_key32_opaque(
476         const struct hwkey_opaque_handle_data* data,
477         uint8_t* kbuf,
478         size_t kbuf_len,
479         size_t* klen) {
480     return get_unittest_key32(kbuf, kbuf_len, klen);
481 }
482 
483 static struct hwkey_opaque_handle_data unittest_opaque_handle_data = {
484         .allowed_uuids = unittest_allowed_opaque_key_uuids,
485         .allowed_uuids_len = countof(unittest_allowed_opaque_key_uuids),
486         .retriever = get_unittest_key32_opaque,
487 };
488 
489 static struct hwkey_opaque_handle_data unittest_opaque_handle_data2 = {
490         .allowed_uuids = unittest_allowed_opaque_key_uuids,
491         .allowed_uuids_len = countof(unittest_allowed_opaque_key_uuids),
492         .retriever = get_unittest_key32_opaque,
493 };
494 
495 static struct hwkey_opaque_handle_data unittest_opaque_handle_data_noaccess = {
496         .allowed_uuids = NULL,
497         .allowed_uuids_len = 0,
498         .retriever = get_unittest_key32_opaque,
499 };
500 
501 /*
502  * Adapter to cast hwkey_opaque_handle_data.priv field to struct
503  * hwkey_derived_keyslot_data*
504  */
get_derived_key_opaque(const struct hwkey_opaque_handle_data * data,uint8_t * kbuf,size_t kbuf_len,size_t * klen)505 static uint32_t get_derived_key_opaque(
506         const struct hwkey_opaque_handle_data* data,
507         uint8_t* kbuf,
508         size_t kbuf_len,
509         size_t* klen) {
510     assert(data);
511     return hwkey_get_derived_key(data->priv, kbuf, kbuf_len, klen);
512 }
513 
514 static struct hwkey_opaque_handle_data unittest_opaque_derived_data = {
515         .allowed_uuids = unittest_allowed_opaque_key_uuids,
516         .allowed_uuids_len = countof(unittest_allowed_opaque_key_uuids),
517         .retriever = get_derived_key_opaque,
518         .priv = &hwcrypto_unittest_derived_data,
519 };
520 
521 #endif /* WITH_HWCRYPTO_UNITTEST */
522 
523 /*
524  *  RPMB Key support
525  */
526 #define RPMB_SS_AUTH_KEY_SIZE 32
527 #define RPMB_SS_AUTH_KEY_ID "com.android.trusty.storage_auth.rpmb"
528 
529 /* Secure storage service app uuid */
530 static const uuid_t ss_uuid = SECURE_STORAGE_SERVER_APP_UUID;
531 
532 static uint8_t rpmb_salt[RPMB_SS_AUTH_KEY_SIZE] = {
533         0x42, 0x18, 0xa9, 0xf2, 0xf6, 0xb1, 0xf5, 0x35, 0x06, 0x37, 0x9f,
534         0xba, 0xcc, 0x1a, 0xc9, 0x36, 0xf4, 0x83, 0x04, 0xd4, 0xf1, 0x65,
535         0x91, 0x32, 0xa6, 0xae, 0xda, 0x27, 0x4d, 0x21, 0xdb, 0x40};
536 
537 /*
538  * Generate RPMB Secure Storage Authentication key
539  */
get_rpmb_ss_auth_key(const struct hwkey_keyslot * slot,uint8_t * kbuf,size_t kbuf_len,size_t * klen)540 static uint32_t get_rpmb_ss_auth_key(const struct hwkey_keyslot* slot,
541                                      uint8_t* kbuf,
542                                      size_t kbuf_len,
543                                      size_t* klen) {
544     int rc;
545     int out_len;
546     EVP_CIPHER_CTX evp;
547 
548     assert(kbuf);
549     assert(klen);
550 
551     EVP_CIPHER_CTX_init(&evp);
552 
553     rc = EVP_EncryptInit_ex(&evp, EVP_aes_256_cbc(), NULL, fake_device_key,
554                             NULL);
555     if (!rc)
556         goto evp_err;
557 
558     rc = EVP_CIPHER_CTX_set_padding(&evp, 0);
559     if (!rc)
560         goto evp_err;
561 
562     size_t min_kbuf_len =
563             RPMB_SS_AUTH_KEY_SIZE + EVP_CIPHER_CTX_key_length(&evp);
564     if (kbuf_len < min_kbuf_len) {
565         TLOGE("buffer too small: (%zd vs. %zd )\n", kbuf_len, min_kbuf_len);
566         goto other_err;
567     }
568 
569     rc = EVP_EncryptUpdate(&evp, kbuf, &out_len, rpmb_salt, sizeof(rpmb_salt));
570     if (!rc)
571         goto evp_err;
572 
573     if ((size_t)out_len != RPMB_SS_AUTH_KEY_SIZE) {
574         TLOGE("output length mismatch (%zd vs %zd)\n", (size_t)out_len,
575               sizeof(rpmb_salt));
576         goto other_err;
577     }
578 
579     rc = EVP_EncryptFinal_ex(&evp, NULL, &out_len);
580     if (!rc)
581         goto evp_err;
582 
583     *klen = RPMB_SS_AUTH_KEY_SIZE;
584 
585     EVP_CIPHER_CTX_cleanup(&evp);
586     return HWKEY_NO_ERROR;
587 
588 evp_err:
589     TLOGE("EVP err 0x%x\n", ERR_get_error());
590 other_err:
591     EVP_CIPHER_CTX_cleanup(&evp);
592     return HWKEY_ERR_GENERIC;
593 }
594 
595 /*
596  * Keymint KAK support
597  */
598 #define KM_KAK_SIZE 32
599 /* TODO import this constant from KM TA when build support is ready */
600 #define KM_KAK_ID "com.android.trusty.keymint.kak"
601 
602 /* KM app uuid */
603 static const uuid_t km_uuid = KM_APP_UUID;
604 
605 /* KM rust app uuid */
606 static const uuid_t km_rust_uuid = KM_RUST_APP_UUID;
607 
608 #if TEST_BUILD
609 /* KM rust unit test uuid */
610 static const uuid_t km_rust_unittest_uuid = KM_RUST_UNITTEST_UUID;
611 
612 /* HWCrypto HAL rust unit test uuid */
613 static const uuid_t hwcryptohal_rust_unittest_uuid =
614         HWCRYPTOHAL_UNITTEST_RUST_APP_UUID;
615 #endif
616 
617 /* HWCrypto HAL rust unit test uuid */
618 static const uuid_t hwcryptohal_rust_uuid = HWCRYPTOHAL_RUST_APP_UUID;
619 
620 static uint8_t kak_salt[KM_KAK_SIZE] = {
621         0x70, 0xc4, 0x7c, 0xfa, 0x2c, 0xb1, 0xee, 0xdc, 0xa5, 0xdf, 0xbc,
622         0x8d, 0xd4, 0xf7, 0x0d, 0x42, 0x93, 0x3b, 0x7f, 0x7b, 0xc2, 0x9e,
623         0x6d, 0xa5, 0xb2, 0x92, 0x7a, 0x21, 0x8e, 0xc9, 0xe6, 0x9a,
624 };
625 
626 /*
627  * This should be replaced with a device-specific implementation such that
628  * any Strongbox on the device will have the same KAK.
629  */
get_km_kak_key(const struct hwkey_keyslot * slot,uint8_t * kbuf,size_t kbuf_len,size_t * klen)630 static uint32_t get_km_kak_key(const struct hwkey_keyslot* slot,
631                                uint8_t* kbuf,
632                                size_t kbuf_len,
633                                size_t* klen) {
634     assert(kbuf);
635     assert(klen);
636 
637     if (kbuf_len < KM_KAK_SIZE) {
638         return HWKEY_ERR_BAD_LEN;
639     }
640     *klen = KM_KAK_SIZE;
641 
642     return derive_key_v1(slot->uuid, kak_salt, KM_KAK_SIZE, kbuf, *klen);
643 }
644 
645 static const uuid_t hwaes_uuid = SAMPLE_HWAES_APP_UUID;
646 
647 #if WITH_HWCRYPTO_UNITTEST
648 static const uuid_t hwaes_unittest_uuid = HWAES_UNITTEST_APP_UUID;
649 static const uuid_t hwaes_bench_uuid = HWAES_BENCH_APP_UUID;
650 
651 static const uuid_t* hwaes_unittest_allowed_opaque_key_uuids[] = {
652         &hwaes_uuid,
653 };
654 
655 static struct hwkey_opaque_handle_data hwaes_unittest_opaque_handle_data = {
656         .allowed_uuids = hwaes_unittest_allowed_opaque_key_uuids,
657         .allowed_uuids_len = countof(hwaes_unittest_allowed_opaque_key_uuids),
658         .retriever = get_unittest_key32_opaque,
659 };
660 #endif
661 
662 /*
663  * Apploader key(s)
664  */
665 struct apploader_key {
666     const uint8_t* key_data;
667 
668     // Pointer to the symbol holding the size of the key.
669     // This needs to be a pointer because the size is not a
670     // constant known to the compiler at compile time,
671     // so it cannot be used to initialize the field directly.
672     const unsigned int* key_size_ptr;
673 };
674 
675 #define INCLUDE_APPLOADER_KEY(key, key_file)   \
676     INCFILE(key##_data, key##_size, key_file); \
677     static struct apploader_key key = {        \
678             .key_data = key##_data,            \
679             .key_size_ptr = &key##_size,       \
680     };
681 
682 #undef APPLOADER_HAS_SIGNING_KEYS
683 #undef APPLOADER_HAS_ENCRYPTION_KEYS
684 
685 #ifdef APPLOADER_SIGN_PUBLIC_KEY_0_FILE
686 INCLUDE_APPLOADER_KEY(apploader_sign_key_0, APPLOADER_SIGN_PUBLIC_KEY_0_FILE);
687 #define APPLOADER_SIGN_KEY_0 "com.android.trusty.apploader.sign.key.0"
688 #define APPLOADER_HAS_SIGNING_KEYS
689 #ifdef APPLOADER_SIGN_KEY_0_UNLOCKED_ONLY
690 #define APPLOADER_SIGN_KEY_0_HANDLER get_apploader_sign_unlocked_key
691 #else
692 #define APPLOADER_SIGN_KEY_0_HANDLER get_apploader_sign_key
693 #endif
694 #endif
695 
696 #ifdef APPLOADER_SIGN_PUBLIC_KEY_1_FILE
697 INCLUDE_APPLOADER_KEY(apploader_sign_key_1, APPLOADER_SIGN_PUBLIC_KEY_1_FILE);
698 #define APPLOADER_SIGN_KEY_1 "com.android.trusty.apploader.sign.key.1"
699 #define APPLOADER_HAS_SIGNING_KEYS
700 #ifdef APPLOADER_SIGN_KEY_1_UNLOCKED_ONLY
701 #define APPLOADER_SIGN_KEY_1_HANDLER get_apploader_sign_unlocked_key
702 #else
703 /*
704  * Rather than rely on a correct build configuration, a real hwkey
705  * implementation should ensure that dev signing keys are not allowed in
706  * unlocked state by either hard-coding dev key slot handlers to a handler that
707  * checks the unlock state or by erroring out here if the build configuration is
708  * unexpected.
709  */
710 #pragma message "Apploader signing key 1 is not gated on unlock status"
711 #define APPLOADER_SIGN_KEY_1_HANDLER get_apploader_sign_key
712 #endif
713 #endif
714 
715 #ifdef APPLOADER_ENCRYPT_KEY_0_FILE
716 INCLUDE_APPLOADER_KEY(apploader_encrypt_key_0, APPLOADER_ENCRYPT_KEY_0_FILE);
717 #define APPLOADER_ENCRYPT_KEY_0 "com.android.trusty.apploader.encrypt.key.0"
718 #define APPLOADER_HAS_ENCRYPTION_KEYS
719 #endif
720 
721 #ifdef APPLOADER_ENCRYPT_KEY_1_FILE
722 INCLUDE_APPLOADER_KEY(apploader_encrypt_key_1, APPLOADER_ENCRYPT_KEY_1_FILE);
723 #define APPLOADER_ENCRYPT_KEY_1 "com.android.trusty.apploader.encrypt.key.1"
724 #define APPLOADER_HAS_ENCRYPTION_KEYS
725 #endif
726 
727 #if defined(APPLOADER_HAS_SIGNING_KEYS) || \
728         defined(APPLOADER_HAS_ENCRYPTION_KEYS)
729 /* Apploader app uuid */
730 static const uuid_t apploader_uuid = APPLOADER_APP_UUID;
731 
get_apploader_key(const struct apploader_key * key,uint8_t * kbuf,size_t kbuf_len,size_t * klen)732 static uint32_t get_apploader_key(const struct apploader_key* key,
733                                   uint8_t* kbuf,
734                                   size_t kbuf_len,
735                                   size_t* klen) {
736     assert(kbuf);
737     assert(klen);
738     assert(key);
739     assert(key->key_size_ptr);
740 
741     size_t key_size = (size_t)*key->key_size_ptr;
742     assert(kbuf_len >= key_size);
743 
744     memcpy(kbuf, key->key_data, key_size);
745     *klen = key_size;
746 
747     return HWKEY_NO_ERROR;
748 }
749 #endif
750 
751 #ifdef APPLOADER_HAS_SIGNING_KEYS
get_apploader_sign_key(const struct hwkey_keyslot * slot,uint8_t * kbuf,size_t kbuf_len,size_t * klen)752 static uint32_t get_apploader_sign_key(const struct hwkey_keyslot* slot,
753                                        uint8_t* kbuf,
754                                        size_t kbuf_len,
755                                        size_t* klen) {
756     assert(slot);
757     return get_apploader_key(slot->priv, kbuf, kbuf_len, klen);
758 }
759 
760 /*
761  * Retrieve the respective key only if the system state APP_LOADING_UNLOCKED
762  * flag is true
763  */
get_apploader_sign_unlocked_key(const struct hwkey_keyslot * slot,uint8_t * kbuf,size_t kbuf_len,size_t * klen)764 static uint32_t get_apploader_sign_unlocked_key(
765         const struct hwkey_keyslot* slot,
766         uint8_t* kbuf,
767         size_t kbuf_len,
768         size_t* klen) {
769     assert(slot);
770     if (system_state_app_loading_unlocked()) {
771         return get_apploader_key(slot->priv, kbuf, kbuf_len, klen);
772     } else {
773         return HWKEY_ERR_NOT_FOUND;
774     }
775 }
776 #endif
777 
778 #ifdef APPLOADER_HAS_ENCRYPTION_KEYS
779 
780 static const uuid_t* apploader_allowed_opaque_key_uuids[] = {
781         &hwaes_uuid,
782 };
783 
784 /* Adapter to cast hwkey_opaque_handle_data.priv to struct apploader_key* */
get_apploader_key_opaque(const struct hwkey_opaque_handle_data * data,uint8_t * kbuf,size_t kbuf_len,size_t * klen)785 static uint32_t get_apploader_key_opaque(
786         const struct hwkey_opaque_handle_data* data,
787         uint8_t* kbuf,
788         size_t kbuf_len,
789         size_t* klen) {
790     assert(data);
791     return get_apploader_key(data->priv, kbuf, kbuf_len, klen);
792 }
793 
794 #ifdef APPLOADER_ENCRYPT_KEY_0
795 static struct hwkey_opaque_handle_data
796         apploader_encrypt_key_0_opaque_handle_data = {
797                 .allowed_uuids = apploader_allowed_opaque_key_uuids,
798                 .allowed_uuids_len =
799                         countof(apploader_allowed_opaque_key_uuids),
800                 .retriever = get_apploader_key_opaque,
801                 .priv = &apploader_encrypt_key_0,
802 };
803 #endif
804 
805 #ifdef APPLOADER_ENCRYPT_KEY_1
806 static struct hwkey_opaque_handle_data
807         apploader_encrypt_key_1_opaque_handle_data = {
808                 .allowed_uuids = apploader_allowed_opaque_key_uuids,
809                 .allowed_uuids_len =
810                         countof(apploader_allowed_opaque_key_uuids),
811                 .retriever = get_apploader_key_opaque,
812                 .priv = &apploader_encrypt_key_1,
813 };
814 #endif
815 
816 #endif
817 
818 static const uuid_t gatekeeper_uuid = GATEKEEPER_APP_UUID;
819 static const uuid_t hwbcc_uuid = SAMPLE_HWBCC_APP_UUID;
820 static const uuid_t hwbcc_unittest_uuid = HWBCC_UNITTEST_APP_UUID;
821 
822 /* Clients that are allowed to connect to this service */
823 static const uuid_t* allowed_clients[] = {
824         /* Needs to derive keys and access keyslot RPMB_SS_AUTH_KEY_ID */
825         &ss_uuid,
826         /* Needs to derive keys and access keyslot KM_KAK_ID */
827         &km_uuid,
828         &km_rust_uuid,
829 #if TEST_BUILD
830         &km_rust_unittest_uuid,
831         /*HWCrypto HAL needs to derive key and access keylots*/
832         &hwcryptohal_rust_unittest_uuid,
833 #endif
834         &hwcryptohal_rust_uuid,
835         /* Needs access to opaque keys */
836         &hwaes_uuid,
837         /* Needs to derive keys */
838         &gatekeeper_uuid,
839 
840 #if defined(APPLOADER_HAS_SIGNING_KEYS) || \
841         defined(APPLOADER_HAS_ENCRYPTION_KEYS)
842         /* Needs to access apploader keys */
843         &apploader_uuid,
844 #endif
845 
846         /* Needs to derive keys even if it doesn't have test keyslots */
847         &hwcrypto_unittest_uuid,
848         &hwcrypto_unittest_rust_uuid,
849 
850 #if WITH_HWCRYPTO_UNITTEST
851         &hwaes_unittest_uuid,
852         &hwaes_bench_uuid,
853 #endif
854         /* Needs to derive keys */
855         &hwbcc_uuid,
856         /* Needs to derive keys */
857         &hwbcc_unittest_uuid,
858 };
859 
860 /*
861  *  List of keys slots that hwkey service supports
862  */
863 static const struct hwkey_keyslot _keys[] = {
864         {
865                 .uuid = &ss_uuid,
866                 .key_id = RPMB_SS_AUTH_KEY_ID,
867                 .handler = get_rpmb_ss_auth_key,
868         },
869         {
870                 .uuid = &km_uuid,
871                 .key_id = KM_KAK_ID,
872                 .handler = get_km_kak_key,
873         },
874         {
875                 .uuid = &km_rust_uuid,
876                 .key_id = KM_KAK_ID,
877                 .handler = get_km_kak_key,
878         },
879 #if TEST_BUILD
880         {
881                 .uuid = &km_rust_unittest_uuid,
882                 .key_id = KM_KAK_ID,
883                 .handler = get_km_kak_key,
884         },
885 #endif
886 #ifdef APPLOADER_SIGN_KEY_0
887         {
888                 .uuid = &apploader_uuid,
889                 .key_id = APPLOADER_SIGN_KEY_0,
890                 .handler = APPLOADER_SIGN_KEY_0_HANDLER,
891                 .priv = &apploader_sign_key_0,
892         },
893 #endif
894 #ifdef APPLOADER_SIGN_KEY_1
895         {
896                 .uuid = &apploader_uuid,
897                 .key_id = APPLOADER_SIGN_KEY_1,
898                 .handler = APPLOADER_SIGN_KEY_1_HANDLER,
899                 .priv = &apploader_sign_key_1,
900         },
901 #endif
902 #ifdef APPLOADER_ENCRYPT_KEY_0
903         {
904                 .uuid = &apploader_uuid,
905                 .key_id = APPLOADER_ENCRYPT_KEY_0,
906                 .handler = get_key_handle,
907                 .priv = &apploader_encrypt_key_0_opaque_handle_data,
908         },
909 #endif
910 #ifdef APPLOADER_ENCRYPT_KEY_1
911         {
912                 .uuid = &apploader_uuid,
913                 .key_id = APPLOADER_ENCRYPT_KEY_1,
914                 .handler = get_key_handle,
915                 .priv = &apploader_encrypt_key_1_opaque_handle_data,
916         },
917 #endif
918 
919 #if WITH_HWCRYPTO_UNITTEST
920         {
921                 .uuid = &hwcrypto_unittest_uuid,
922                 .key_id = "com.android.trusty.hwcrypto.unittest.key32",
923                 .handler = get_unittest_key32_handler,
924         },
925         {
926                 .uuid = &hwcrypto_unittest_rust_uuid,
927                 .key_id = "com.android.trusty.hwcrypto.unittest.key32",
928                 .handler = get_unittest_key32_handler,
929         },
930         {
931                 .uuid = &hwcrypto_unittest_uuid,
932                 .key_id = "com.android.trusty.hwcrypto.unittest.derived_key32",
933                 .priv = &hwcrypto_unittest_derived_data,
934                 .handler = derived_keyslot_handler,
935         },
936         {
937                 .uuid = &hwcrypto_unittest_rust_uuid,
938                 .key_id = "com.android.trusty.hwcrypto.unittest.derived_key32",
939                 .priv = &hwcrypto_unittest_derived_data,
940                 .handler = derived_keyslot_handler,
941         },
942         {
943                 .uuid = &hwcrypto_unittest_uuid,
944                 .key_id = "com.android.trusty.hwcrypto.unittest.opaque_handle",
945                 .handler = get_key_handle,
946                 .priv = &unittest_opaque_handle_data,
947         },
948         {
949                 .uuid = &hwcrypto_unittest_rust_uuid,
950                 .key_id = "com.android.trusty.hwcrypto.unittest.opaque_handle",
951                 .handler = get_key_handle,
952                 .priv = &unittest_opaque_handle_data,
953         },
954         {
955                 .uuid = &hwcrypto_unittest_uuid,
956                 .key_id = "com.android.trusty.hwcrypto.unittest.opaque_handle2",
957                 .handler = get_key_handle,
958                 .priv = &unittest_opaque_handle_data2,
959         },
960         {
961                 .uuid = &hwcrypto_unittest_rust_uuid,
962                 .key_id = "com.android.trusty.hwcrypto.unittest.opaque_handle2",
963                 .handler = get_key_handle,
964                 .priv = &unittest_opaque_handle_data2,
965         },
966         {
967                 .uuid = &hwcrypto_unittest_uuid,
968                 .key_id =
969                         "com.android.trusty.hwcrypto.unittest.opaque_handle_noaccess",
970                 .handler = get_key_handle,
971                 .priv = &unittest_opaque_handle_data_noaccess,
972         },
973         {
974                 .uuid = &hwcrypto_unittest_rust_uuid,
975                 .key_id =
976                         "com.android.trusty.hwcrypto.unittest.opaque_handle_noaccess",
977                 .handler = get_key_handle,
978                 .priv = &unittest_opaque_handle_data_noaccess,
979         },
980         {
981                 .uuid = &hwcrypto_unittest_uuid,
982                 .key_id = "com.android.trusty.hwcrypto.unittest.opaque_derived",
983                 .handler = get_key_handle,
984                 .priv = &unittest_opaque_derived_data,
985         },
986         {
987                 .uuid = &hwcrypto_unittest_rust_uuid,
988                 .key_id = "com.android.trusty.hwcrypto.unittest.opaque_derived",
989                 .handler = get_key_handle,
990                 .priv = &unittest_opaque_derived_data,
991         },
992         {
993                 .uuid = &hwaes_unittest_uuid,
994                 .key_id = "com.android.trusty.hwaes.unittest.opaque_handle",
995                 .handler = get_key_handle,
996                 .priv = &hwaes_unittest_opaque_handle_data,
997         },
998         {
999                 .uuid = &hwaes_bench_uuid,
1000                 .key_id = "com.android.trusty.hwaes.unittest.opaque_handle",
1001                 .handler = get_key_handle,
1002                 .priv = &hwaes_unittest_opaque_handle_data,
1003         },
1004 #endif /* WITH_HWCRYPTO_UNITTEST */
1005 };
1006 
1007 /*
1008  *  Run Self test
1009  */
hwkey_self_test(void)1010 static bool hwkey_self_test(void) {
1011     TLOGI("hwkey self test\n");
1012 
1013     if (!hkdf_self_test())
1014         return false;
1015 
1016     TLOGI("hwkey self test: PASSED\n");
1017     return true;
1018 }
1019 
1020 /*
1021  *  Initialize HWKEY service
1022  */
hwkey_start_service(struct tipc_hset * hset)1023 static int hwkey_start_service(struct tipc_hset* hset) {
1024     TLOGD("Start HWKEY service\n");
1025 
1026     static struct tipc_port_acl acl = {
1027             .flags = IPC_PORT_ALLOW_TA_CONNECT,
1028             .uuid_num = countof(allowed_clients),
1029             .uuids = allowed_clients,
1030     };
1031 
1032     static struct tipc_port port = {
1033             .name = HWKEY_PORT,
1034             .msg_max_size = HWKEY_MAX_MSG_SIZE,
1035             .msg_queue_len = 1,
1036             .acl = &acl,
1037     };
1038 
1039     static struct tipc_srv_ops ops = {
1040             .on_message = hwkey_chan_handle_msg,
1041             .on_connect = hwkey_chan_ctx_create,
1042             .on_channel_cleanup = hwkey_chan_ctx_close,
1043     };
1044 
1045     return tipc_add_service(hset, &port, 1, HWKEY_MAX_NUM_CHANNELS, &ops);
1046 }
1047 
1048 /*
1049  *  Initialize Fake HWKEY service provider
1050  */
hwkey_init_srv_provider(struct tipc_hset * hset)1051 int hwkey_init_srv_provider(struct tipc_hset* hset) {
1052     int rc;
1053 
1054     TLOGE("Init FAKE!!!! HWKEY service provider\n");
1055     TLOGE("FAKE HWKEY service provider MUST be replaced with the REAL one\n");
1056 
1057     /* run self test */
1058     if (!hwkey_self_test()) {
1059         TLOGE("hwkey_self_test failed\n");
1060         abort();
1061     }
1062 
1063     /* install key handlers */
1064     hwkey_install_keys(_keys, countof(_keys));
1065 
1066     /* start service */
1067     rc = hwkey_start_service(hset);
1068     if (rc != NO_ERROR) {
1069         TLOGE("failed (%d) to start HWKEY service\n", rc);
1070     }
1071 
1072     return rc;
1073 }
1074