1 /*
2  * Copyright (C) 2024 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 #[cfg(test)]
17 mod tests {
18     use android_hardware_security_see::aidl::android::hardware::security::see::hwcrypto::{
19         IHwCryptoKey::{
20             DerivedKey::DerivedKey, DerivedKeyParameters::DerivedKeyParameters,
21             DerivedKeyPolicy::DerivedKeyPolicy, DeviceKeyId::DeviceKeyId,
22             DiceBoundDerivationKey::DiceBoundDerivationKey, DiceBoundKeyResult::DiceBoundKeyResult,
23             DiceCurrentBoundKeyResult::DiceCurrentBoundKeyResult, IHwCryptoKey,
24             ClearKeyPolicy::ClearKeyPolicy,
25         },
26     };
27     use binder::{StatusCode, Strong};
28     use rpcbinder::RpcSession;
29     use test::{expect, assert_ok};
30     use trusty_std::ffi::{CString, FallibleCString};
31 
32     pub(crate) const RUST_DEVICE_KEY_SERVICE_PORT: &str = "com.android.trusty.rust.hwcryptohal.V1";
33 
34     pub(crate) const VERSION_0_DICE_POLICY: [u8; 120] = [
35         0x83, 0x58, 0x30, 0xa3, 0x01, 0x03, 0x3a, 0x00, 0x01, 0x00, 0x02, 0x58, 0x20, 0x7a, 0x87,
36         0x07, 0x18, 0x72, 0x14, 0xb4, 0x1e, 0x69, 0x60, 0xc8, 0x6e, 0xfd, 0x8d, 0xdf, 0x6e, 0x48,
37         0xbd, 0x33, 0xa2, 0xdf, 0x6c, 0x76, 0x59, 0xdf, 0x82, 0x93, 0x3e, 0xf3, 0xa9, 0x6a, 0x23,
38         0x3a, 0x00, 0x01, 0x00, 0x03, 0x01, 0xa0, 0x58, 0x42, 0xea, 0xf7, 0x26, 0xfd, 0x2a, 0x06,
39         0x0a, 0x4b, 0x9e, 0x8c, 0xba, 0xf3, 0x41, 0x91, 0xac, 0x88, 0xfd, 0xc6, 0x23, 0xc3, 0x3f,
40         0x33, 0x64, 0x6d, 0x20, 0xb4, 0x18, 0x7a, 0x55, 0x7c, 0x4c, 0xdd, 0x64, 0x84, 0x54, 0x22,
41         0xec, 0xd9, 0x1d, 0x89, 0x49, 0xf3, 0xcb, 0x37, 0xfb, 0x1c, 0x49, 0x5a, 0xd5, 0xbc, 0xf6,
42         0x82, 0xd7, 0x82, 0xcc, 0x51, 0x00, 0x3b, 0x71, 0x0f, 0xde, 0xdb, 0x8a, 0xcf, 0x23, 0xf9,
43     ];
44 
45     pub(crate) const VERSION_0_CLEAR_KEY: [u8; 256] = [
46         0xf7, 0xf3, 0x3f, 0x34, 0xfd, 0x4c, 0x09, 0xcf, 0xb2, 0x20, 0x8a, 0xcc, 0x08, 0xd8, 0x33,
47         0x97, 0x66, 0xeb, 0x65, 0xd2, 0xba, 0xd9, 0x48, 0x83, 0x79, 0x6d, 0x43, 0x09, 0x69, 0xe5,
48         0x2d, 0x54, 0x9b, 0xd8, 0xbb, 0xc0, 0xb9, 0xec, 0xe4, 0x90, 0x8b, 0x43, 0x57, 0x9b, 0x84,
49         0xad, 0x55, 0xd5, 0x68, 0x43, 0xc6, 0x1b, 0x01, 0x36, 0xca, 0x82, 0x6c, 0x96, 0xae, 0x5f,
50         0xca, 0xec, 0xc2, 0x48, 0x13, 0x5a, 0x72, 0x17, 0x20, 0x56, 0x9e, 0x3b, 0xe3, 0xe5, 0xbd,
51         0x20, 0x38, 0x56, 0x01, 0x8a, 0x32, 0x92, 0x47, 0xb1, 0x0f, 0x0e, 0x8f, 0x69, 0x1d, 0x7f,
52         0x33, 0x84, 0xb8, 0x46, 0x58, 0x0d, 0xf6, 0xa2, 0xb1, 0xc7, 0xe9, 0x7a, 0xbc, 0x18, 0xa9,
53         0x78, 0x70, 0x61, 0xff, 0x4b, 0x70, 0x41, 0x58, 0xdd, 0xbb, 0xcb, 0x71, 0x46, 0x92, 0x4d,
54         0xf2, 0x26, 0xe0, 0x20, 0x6d, 0x81, 0x4c, 0x82, 0x5a, 0x29, 0xee, 0x1e, 0x01, 0xb7, 0xd1,
55         0x8b, 0x32, 0xef, 0x00, 0x5e, 0x83, 0x1e, 0x30, 0x1d, 0xc4, 0xb2, 0x95, 0x5a, 0xa5, 0x75,
56         0x02, 0x9c, 0xae, 0xf5, 0x8e, 0x88, 0xd8, 0x94, 0xac, 0x9a, 0x04, 0x88, 0x6f, 0x38, 0x8b,
57         0x1b, 0x22, 0x5a, 0x33, 0x3e, 0xfb, 0x2e, 0xfd, 0x6f, 0xaa, 0x7d, 0xcd, 0xf1, 0xab, 0x61,
58         0x69, 0xc0, 0x54, 0x09, 0xf9, 0xe9, 0x43, 0xa1, 0x7f, 0x48, 0xf5, 0xe9, 0xfe, 0xf3, 0xd5,
59         0xd1, 0xdf, 0x0c, 0xe7, 0xc9, 0xd4, 0xfd, 0xe2, 0x31, 0x33, 0x6c, 0x71, 0xe1, 0xe0, 0x9b,
60         0x35, 0x1f, 0xea, 0x7a, 0x3e, 0xaa, 0x36, 0x70, 0xda, 0xb7, 0xcc, 0x5e, 0x1f, 0xe5, 0x70,
61         0xf6, 0x60, 0xe8, 0xa4, 0x8a, 0xa3, 0x1d, 0x08, 0x6a, 0xa6, 0xf9, 0x6c, 0xac, 0x5b, 0xa2,
62         0xa9, 0x45, 0x67, 0xae, 0x34, 0x55, 0xc0, 0xd0, 0xf5, 0x37, 0xde, 0xc6, 0x13, 0x06, 0x16,
63         0x82,
64     ];
65 
connect() -> Result<Strong<dyn IHwCryptoKey>, StatusCode>66     fn connect() -> Result<Strong<dyn IHwCryptoKey>, StatusCode> {
67         let port =
68             CString::try_new(RUST_DEVICE_KEY_SERVICE_PORT).expect("Failed to allocate port name");
69         RpcSession::new().setup_trusty_client(port.as_c_str())
70     }
71 
keys_are_sufficiently_distinct(key1: Vec<u8>, key2: Vec<u8>) -> bool72     fn keys_are_sufficiently_distinct(key1: Vec<u8>, key2: Vec<u8>) -> bool {
73         let differing_bytes = key1.iter().zip(key2.iter()).filter(|(&x1, &x2)| x1 != x2).count();
74 
75         std::cmp::min(key1.len(), key2.len()) - differing_bytes <= 4
76     }
77 
78     #[test]
generate_new_policy_and_clear_key()79     fn generate_new_policy_and_clear_key() {
80         let hw_device_key = connect().expect("couldn't connect to HW Crypto service");
81 
82         // Get the device bound key
83         let device_bound_key = DiceBoundDerivationKey::KeyId(DeviceKeyId::DEVICE_BOUND_KEY);
84 
85         // Generate the current derivation key and policy
86         let key_and_policy =
87             assert_ok!(hw_device_key.deriveCurrentDicePolicyBoundKey(&device_bound_key));
88         let DiceCurrentBoundKeyResult {
89             diceBoundKey: derivation_key1,
90             dicePolicyForKeyVersion: dice_policy,
91         } = key_and_policy;
92 
93         expect!(derivation_key1.is_some(), "should have received a key");
94         expect!(dice_policy.len() > 0, "should have received a DICE policy");
95 
96         // Derive a clear key from returned current policy and derivation key
97         let mut params = DerivedKeyParameters {
98             derivationKey: derivation_key1,
99             keyPolicy: DerivedKeyPolicy::ClearKey(ClearKeyPolicy { keySizeBytes: 256 }),
100             context: "context".as_bytes().to_vec(),
101         };
102 
103         let derived_key1 = assert_ok!(hw_device_key.deriveKey(&params));
104 
105         // Check key type and length
106         let derived_key1 = match derived_key1 {
107             DerivedKey::Opaque(_) => panic!("wrong type of key received"),
108             DerivedKey::ExplicitKey(k) => k,
109         };
110 
111         assert_eq!(derived_key1.len() as i32, 256, "wrong key length");
112 
113         // Use dice policy to request same key
114         let key_and_policy =
115             assert_ok!(hw_device_key.deriveDicePolicyBoundKey(&device_bound_key, &dice_policy));
116         let DiceBoundKeyResult {
117             diceBoundKey: derivation_key2,
118             dicePolicyWasCurrent: dice_policy_current,
119         } = key_and_policy;
120 
121         expect!(derivation_key2.is_some(), "should have received a key");
122         expect!(dice_policy_current, "policy should have been current");
123 
124         // generate derived key 2 and compare to key 1
125         params.derivationKey = derivation_key2;
126 
127         let derived_key2 = assert_ok!(hw_device_key.deriveKey(&params));
128 
129         // Check key type and length
130         let derived_key2 = match derived_key2 {
131             DerivedKey::Opaque(_) => panic!("wrong type of key received"),
132             DerivedKey::ExplicitKey(k) => k,
133         };
134 
135         assert_eq!(derived_key2.len() as i32, 256, "wrong key length");
136 
137         // Make sure both derived keys match
138         assert_eq!(derived_key2, derived_key1, "key mismatch");
139 
140         // If we request current dice policy again, we expect the same key, but different
141         // encryption of the returned policy. Note underlying policy is the same (latest),
142         // but encrypted byte array returned will be different
143 
144         // Generate the current derivation key and policy again
145         let key_and_policy =
146             assert_ok!(hw_device_key.deriveCurrentDicePolicyBoundKey(&device_bound_key));
147         let DiceCurrentBoundKeyResult {
148             diceBoundKey: derivation_key3,
149             dicePolicyForKeyVersion: dice_policy3,
150         } = key_and_policy;
151 
152         // We expect the dice policy to appear different due to encruption
153         assert_ne!(
154             dice_policy, dice_policy3,
155             "expected dice policies to appear different due to encryption"
156         );
157 
158         // Ensure derived key from this policy matches previously generated derived key
159         params.derivationKey = derivation_key3;
160 
161         let derived_key3 = assert_ok!(hw_device_key.deriveKey(&params));
162 
163         // Check key type and length
164         let derived_key3 = match derived_key3 {
165             DerivedKey::Opaque(_) => panic!("wrong type of key received"),
166             DerivedKey::ExplicitKey(k) => k,
167         };
168 
169         assert_eq!(derived_key3.len() as i32, 256, "wrong key length");
170 
171         // Make sure both derived keys match
172         assert_eq!(derived_key3, derived_key1, "key mismatch");
173     }
174 
175     #[test]
old_dice_generates_old_clear_key_and_new_policy()176     fn old_dice_generates_old_clear_key_and_new_policy() {
177         let hw_device_key = connect().expect("couldn't connect to HW Crypto service");
178 
179         // Get the device bound key
180         let device_bound_key = DiceBoundDerivationKey::KeyId(DeviceKeyId::DEVICE_BOUND_KEY);
181 
182         // Generate a derived key from version 0 dice policy
183         let key_and_policy = assert_ok!(
184             hw_device_key.deriveDicePolicyBoundKey(&device_bound_key, &VERSION_0_DICE_POLICY)
185         );
186         let DiceBoundKeyResult {
187             diceBoundKey: derivation_key,
188             dicePolicyWasCurrent: dice_policy_current,
189         } = key_and_policy;
190 
191         // We expect version 0 should not be current
192         expect!(!dice_policy_current, "policy not expected to be current");
193 
194         // Derive clear key from derivation key
195         let params = DerivedKeyParameters {
196             derivationKey: derivation_key,
197             keyPolicy: DerivedKeyPolicy::ClearKey(ClearKeyPolicy { keySizeBytes: 256 }),
198             context: "context".as_bytes().to_vec(),
199         };
200 
201         let derived_key = assert_ok!(hw_device_key.deriveKey(&params));
202 
203         // Check key type and length
204         let derived_key = match derived_key {
205             DerivedKey::Opaque(_) => panic!("wrong type of key received"),
206             DerivedKey::ExplicitKey(k) => k,
207         };
208 
209         assert_eq!(derived_key.len() as i32, 256, "wrong key length");
210 
211         // Check we got the old key and a new policy
212         assert_eq!(derived_key, VERSION_0_CLEAR_KEY.to_vec(), "Retrieved version 0 key mismatch");
213     }
214 
215     #[test]
dice_updates_are_unique()216     fn dice_updates_are_unique() {
217         let hw_device_key = connect().expect("couldn't connect to HW Crypto service");
218 
219         // Get the device bound key
220         let device_bound_key = DiceBoundDerivationKey::KeyId(DeviceKeyId::DEVICE_BOUND_KEY);
221 
222         // Generate a derived key from version 0 dice policy
223         let key_and_policy = assert_ok!(
224             hw_device_key.deriveDicePolicyBoundKey(&device_bound_key, &VERSION_0_DICE_POLICY)
225         );
226         let DiceBoundKeyResult {
227             diceBoundKey: _derivation_key,
228             dicePolicyWasCurrent: dice_policy_current,
229         } = key_and_policy;
230 
231         // We expect version 0 should not be current
232         expect!(!dice_policy_current, "policy not expected to be current");
233 
234         // Get current dice policy multiple times
235         let key_and_policy =
236             assert_ok!(hw_device_key.deriveCurrentDicePolicyBoundKey(&device_bound_key));
237         let DiceCurrentBoundKeyResult {
238             diceBoundKey: derivation_key1,
239             dicePolicyForKeyVersion: dice_policy1,
240         } = key_and_policy;
241 
242         let key_and_policy =
243             assert_ok!(hw_device_key.deriveCurrentDicePolicyBoundKey(&device_bound_key));
244         let DiceCurrentBoundKeyResult {
245             diceBoundKey: derivation_key2,
246             dicePolicyForKeyVersion: dice_policy2,
247         } = key_and_policy;
248 
249         // policies should appear different due to encryption and not be zero length
250         expect!(dice_policy1.len() > 0, "should have received a DICE policy");
251         expect!(dice_policy2.len() > 0, "should have received a DICE policy");
252         assert_ne!(dice_policy1, dice_policy2, "expected policies to be different");
253 
254         expect!(derivation_key1.is_some(), "should have received a key");
255         expect!(derivation_key2.is_some(), "should have received a key");
256 
257         // Generate derived clear keys from returned derivation keys
258         let params = DerivedKeyParameters {
259             derivationKey: derivation_key1,
260             keyPolicy: DerivedKeyPolicy::ClearKey(ClearKeyPolicy { keySizeBytes: 256 }),
261             context: "context".as_bytes().to_vec(),
262         };
263 
264         let derived_key1 = assert_ok!(hw_device_key.deriveKey(&params));
265 
266         let params = DerivedKeyParameters {
267             derivationKey: derivation_key2,
268             keyPolicy: DerivedKeyPolicy::ClearKey(ClearKeyPolicy { keySizeBytes: 256 }),
269             context: "context".as_bytes().to_vec(),
270         };
271 
272         let derived_key2 = assert_ok!(hw_device_key.deriveKey(&params));
273 
274         // Check derived keys
275         let derived_key1 = match derived_key1 {
276             DerivedKey::Opaque(_) => panic!("wrong type of key received"),
277             DerivedKey::ExplicitKey(k) => k,
278         };
279 
280         let derived_key2 = match derived_key2 {
281             DerivedKey::Opaque(_) => panic!("wrong type of key received"),
282             DerivedKey::ExplicitKey(k) => k,
283         };
284 
285         // Check that generated keys match
286         assert_eq!(derived_key1, derived_key2, "key mismatch");
287 
288         // Check that both dice policies are considered current
289         let key_and_policy =
290             assert_ok!(hw_device_key.deriveDicePolicyBoundKey(&device_bound_key, &dice_policy1));
291         let DiceBoundKeyResult { diceBoundKey: _, dicePolicyWasCurrent: dice_policy1_current } =
292             key_and_policy;
293 
294         expect!(dice_policy1_current, "policy expected to be current");
295 
296         let key_and_policy =
297             assert_ok!(hw_device_key.deriveDicePolicyBoundKey(&device_bound_key, &dice_policy2));
298         let DiceBoundKeyResult { diceBoundKey: _, dicePolicyWasCurrent: dice_policy2_current } =
299             key_and_policy;
300 
301         expect!(dice_policy2_current, "policy expected to be current");
302     }
303 
304     #[test]
explicit_keys_unique_by_context()305     fn explicit_keys_unique_by_context() {
306         let hw_device_key = connect().expect("couldn't connect to HW Crypto service");
307 
308         // Get the device bound key
309         let device_bound_key = DiceBoundDerivationKey::KeyId(DeviceKeyId::DEVICE_BOUND_KEY);
310 
311         // Generate the current derivation key and policy
312         let key_and_policy =
313             assert_ok!(hw_device_key.deriveCurrentDicePolicyBoundKey(&device_bound_key));
314         let DiceCurrentBoundKeyResult {
315             diceBoundKey: derivation_key,
316             dicePolicyForKeyVersion: dice_policy,
317         } = key_and_policy;
318 
319         expect!(derivation_key.is_some(), "should have received a key");
320         expect!(dice_policy.len() > 0, "should have received a DICE policy");
321 
322         // Define two different contexts and get clear derived keys for each
323         let context1 = "context1";
324         let context2 = "context2";
325 
326         let params1 = DerivedKeyParameters {
327             derivationKey: derivation_key.clone(),
328             keyPolicy: DerivedKeyPolicy::ClearKey(ClearKeyPolicy { keySizeBytes: 256 }),
329             context: context1.as_bytes().to_vec(),
330         };
331 
332         let params2 = DerivedKeyParameters {
333             derivationKey: derivation_key.clone(),
334             keyPolicy: DerivedKeyPolicy::ClearKey(ClearKeyPolicy { keySizeBytes: 256 }),
335             context: context2.as_bytes().to_vec(),
336         };
337 
338         let derived_key1 = assert_ok!(hw_device_key.deriveKey(&params1));
339         let derived_key2 = assert_ok!(hw_device_key.deriveKey(&params2));
340 
341         // Check key2 type and length
342         let derived_key1 = match derived_key1 {
343             DerivedKey::Opaque(_) => panic!("wrong type of key received"),
344             DerivedKey::ExplicitKey(k) => k,
345         };
346 
347         let derived_key2 = match derived_key2 {
348             DerivedKey::Opaque(_) => panic!("wrong type of key received"),
349             DerivedKey::ExplicitKey(k) => k,
350         };
351 
352         assert_eq!(derived_key1.len() as i32, 256, "wrong key length");
353         assert_eq!(derived_key2.len() as i32, 256, "wrong key length");
354 
355         // Ensure keys are different
356         assert_ne!(derived_key2, derived_key1, "returned keys are same");
357         assert!(
358             keys_are_sufficiently_distinct(derived_key2, derived_key1),
359             "derived keys share too many bytes"
360         );
361     }
362 
363     #[test]
invalid_key_sizes()364     fn invalid_key_sizes() {
365         let hw_device_key = connect().expect("couldn't connect to HW Crypto service");
366 
367         // Get the device bound key
368         let device_bound_key = DiceBoundDerivationKey::KeyId(DeviceKeyId::DEVICE_BOUND_KEY);
369 
370         // Generate the current derivation key and policy
371         let key_and_policy =
372             assert_ok!(hw_device_key.deriveCurrentDicePolicyBoundKey(&device_bound_key));
373         let DiceCurrentBoundKeyResult {
374             diceBoundKey: derivation_key,
375             dicePolicyForKeyVersion: dice_policy,
376         } = key_and_policy;
377 
378         expect!(derivation_key.is_some(), "should have received a key");
379         expect!(dice_policy.len() > 0, "should have received a DICE policy");
380 
381         // Request a zero length key
382         let params = DerivedKeyParameters {
383             derivationKey: derivation_key.clone(),
384             keyPolicy: DerivedKeyPolicy::ClearKey(ClearKeyPolicy { keySizeBytes: 0 }),
385             context: "context".as_bytes().to_vec(),
386         };
387 
388         let derived_key = hw_device_key.deriveKey(&params);
389         expect!(derived_key.is_err(), "expected error on bad key size");
390 
391         // Request a negative length key
392         let params = DerivedKeyParameters {
393             derivationKey: derivation_key.clone(),
394             keyPolicy: DerivedKeyPolicy::ClearKey(ClearKeyPolicy { keySizeBytes: -256 }),
395             context: "context".as_bytes().to_vec(),
396         };
397 
398         let derived_key = hw_device_key.deriveKey(&params);
399         expect!(derived_key.is_err(), "expected error on bad key size");
400     }
401 
402     #[test]
large_context()403     fn large_context() {
404         let hw_device_key = connect().expect("couldn't connect to HW Crypto service");
405 
406         // Get the device bound key
407         let device_bound_key = DiceBoundDerivationKey::KeyId(DeviceKeyId::DEVICE_BOUND_KEY);
408 
409         // Generate the current derivation key and policy
410         let key_and_policy =
411             assert_ok!(hw_device_key.deriveCurrentDicePolicyBoundKey(&device_bound_key));
412         let DiceCurrentBoundKeyResult {
413             diceBoundKey: derivation_key,
414             dicePolicyForKeyVersion: dice_policy,
415         } = key_and_policy;
416 
417         expect!(derivation_key.is_some(), "should have received a key");
418         expect!(dice_policy.len() > 0, "should have received a DICE policy");
419 
420         // Pick a reasonable large context size
421         const PAYLOAD_LEN: usize = 512;
422 
423         let mut context = vec![42; PAYLOAD_LEN];
424 
425         // Get a derived key based on large context
426         let params = DerivedKeyParameters {
427             derivationKey: derivation_key.clone(),
428             keyPolicy: DerivedKeyPolicy::ClearKey(ClearKeyPolicy { keySizeBytes: 256 }),
429             context: context.clone(),
430         };
431 
432         let derived_key1 = assert_ok!(hw_device_key.deriveKey(&params));
433 
434         // Check key type and length
435         let derived_key1 = match derived_key1 {
436             DerivedKey::Opaque(_) => panic!("wrong type of key received"),
437             DerivedKey::ExplicitKey(k) => k,
438         };
439 
440         assert_eq!(derived_key1.len() as i32, 256, "wrong key length");
441 
442         // Make a minor change to last byte of context and request another key
443         context[PAYLOAD_LEN - 1] = 43;
444 
445         let params = DerivedKeyParameters {
446             derivationKey: derivation_key.clone(),
447             keyPolicy: DerivedKeyPolicy::ClearKey(ClearKeyPolicy { keySizeBytes: 256 }),
448             context: context.clone(),
449         };
450 
451         let derived_key2 = assert_ok!(hw_device_key.deriveKey(&params));
452 
453         // Check key type and length
454         let derived_key2 = match derived_key2 {
455             DerivedKey::Opaque(_) => panic!("wrong type of key received"),
456             DerivedKey::ExplicitKey(k) => k,
457         };
458 
459         assert_eq!(derived_key2.len() as i32, 256, "wrong key length");
460 
461         //Ensure keys are different
462         assert_ne!(derived_key1, derived_key2, "keys expected to differ");
463         assert!(
464             keys_are_sufficiently_distinct(derived_key1, derived_key2),
465             "derived keys share too many bytes"
466         );
467     }
468 }
469