1 /*
2 * Copyright (C) 2023 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 //! A “DICE policy” is a format for setting constraints on a DICE chain. A DICE chain policy
18 //! verifier takes a policy and a DICE chain, and returns a boolean indicating whether the
19 //! DICE chain meets the constraints set out on a policy.
20 //!
21 //! This forms the foundation of Dice Policy aware Authentication (DPA-Auth), where the server
22 //! authenticates a client by comparing its dice chain against a set policy.
23 //!
24 //! Another use is "sealing", where clients can use an appropriately constructed dice policy to
25 //! seal a secret. Unsealing is only permitted if dice chain of the component requesting unsealing
26 //! complies with the policy.
27 //!
28 //! A typical policy will assert things like:
29 //! # DK_pub must have this value
30 //! # The DICE chain must be exactly five certificates long
31 //! # authorityHash in the third certificate must have this value
32 //! securityVersion in the fourth certificate must be an integer greater than 8
33 //!
34 //! These constraints used to express policy are (for now) limited to following 2 types:
35 //! 1. Exact Match: useful for enforcing rules like authority hash should be exactly equal.
36 //! 2. Greater than or equal to: Useful for setting policies that seal
37 //! Anti-rollback protected entities (should be accessible to versions >= present).
38 //!
39 //! Dice Policy CDDL (keep in sync with DicePolicy.cddl):
40 //!
41 //! ```
42 //! dicePolicy = [
43 //! 1, ; dice policy version
44 //! + nodeConstraintList ; for each entry in dice chain
45 //! ]
46 //!
47 //! nodeConstraintList = [
48 //! * nodeConstraint
49 //! ]
50 //!
51 //! ; We may add a hashConstraint item later
52 //! nodeConstraint = exactMatchConstraint / geConstraint
53 //!
54 //! exactMatchConstraint = [1, keySpec, value]
55 //! geConstraint = [2, keySpec, int]
56 //!
57 //! keySpec = [value+]
58 //!
59 //! value = bool / int / tstr / bstr
60 //! ```
61
62 use ciborium::Value;
63 use coset::{AsCborValue, CborSerializable, CoseError, CoseError::UnexpectedItem, CoseSign1};
64 use std::borrow::Cow;
65 use std::iter::zip;
66
67 type Error = String;
68
69 /// Version of the Dice policy spec
70 pub const DICE_POLICY_VERSION: u64 = 1;
71 /// Identifier for `exactMatchConstraint` as per spec
72 pub const EXACT_MATCH_CONSTRAINT: u16 = 1;
73 /// Identifier for `geConstraint` as per spec
74 pub const GREATER_OR_EQUAL_CONSTRAINT: u16 = 2;
75
76 /// Given an Android dice chain, check if it matches the given policy. This method returns
77 /// Ok(()) in case of successful match, otherwise returns error in case of failure.
chain_matches_policy(dice_chain: &[u8], policy: &[u8]) -> Result<(), Error>78 pub fn chain_matches_policy(dice_chain: &[u8], policy: &[u8]) -> Result<(), Error> {
79 DicePolicy::from_slice(policy)
80 .map_err(|e| format!("DicePolicy decoding failed {e:?}"))?
81 .matches_dice_chain(dice_chain)
82 .map_err(|e| format!("DicePolicy matching failed {e:?}"))?;
83 Ok(())
84 }
85
86 // TODO(b/291238565): (nested_)key & value type should be (bool/int/tstr/bstr). Status quo, only
87 // integer (nested_)key is supported.
88 // and maybe convert it into struct.
89 /// Each constraint (on a dice node) is a tuple: (ConstraintType, constraint_path, value)
90 /// This is Rust equivalent of `nodeConstraint` from CDDL above. Keep in sync!
91 #[derive(Clone, Debug, PartialEq)]
92 pub struct Constraint(u16, Vec<i64>, Value);
93
94 impl Constraint {
95 /// Construct a new Constraint
new(constraint_type: u16, path: Vec<i64>, value: Value) -> Result<Self, Error>96 pub fn new(constraint_type: u16, path: Vec<i64>, value: Value) -> Result<Self, Error> {
97 if constraint_type != EXACT_MATCH_CONSTRAINT
98 && constraint_type != GREATER_OR_EQUAL_CONSTRAINT
99 {
100 return Err(format!("Invalid Constraint type: {constraint_type}"));
101 }
102 Ok(Self(constraint_type, path, value))
103 }
104 }
105
106 impl AsCborValue for Constraint {
from_cbor_value(value: Value) -> Result<Self, CoseError>107 fn from_cbor_value(value: Value) -> Result<Self, CoseError> {
108 let [constrained_type, constraint_path, val] = value
109 .into_array()
110 .map_err(|_| UnexpectedItem("-", "Array"))?
111 .try_into()
112 .map_err(|_| UnexpectedItem("Array", "Array of size 3"))?;
113 let constrained_type: u16 = value_to_integer(&constrained_type)?
114 .try_into()
115 .map_err(|_| UnexpectedItem("Integer", "u16"))?;
116 let path_res: Vec<i64> = constraint_path
117 .into_array()
118 .map_err(|_| UnexpectedItem("-", "Array"))?
119 .iter()
120 .map(value_to_integer)
121 .collect::<Result<_, _>>()?;
122 Ok(Self(constrained_type, path_res, val))
123 }
124
to_cbor_value(self) -> Result<Value, CoseError>125 fn to_cbor_value(self) -> Result<Value, CoseError> {
126 Ok(Value::Array(vec![
127 Value::from(self.0),
128 Value::Array(self.1.into_iter().map(Value::from).collect()),
129 self.2,
130 ]))
131 }
132 }
133
134 /// List of all constraints on a dice node.
135 /// This is Rust equivalent of `nodeConstraintList` in the CDDL above. Keep in sync!
136 #[derive(Clone, Debug, PartialEq)]
137 pub struct NodeConstraints(pub Box<[Constraint]>);
138
139 impl AsCborValue for NodeConstraints {
from_cbor_value(value: Value) -> Result<Self, CoseError>140 fn from_cbor_value(value: Value) -> Result<Self, CoseError> {
141 let res: Vec<Constraint> = value
142 .into_array()
143 .map_err(|_| UnexpectedItem("-", "Array"))?
144 .into_iter()
145 .map(Constraint::from_cbor_value)
146 .collect::<Result<_, _>>()?;
147 Ok(Self(res.into_boxed_slice()))
148 }
149
to_cbor_value(self) -> Result<Value, CoseError>150 fn to_cbor_value(self) -> Result<Value, CoseError> {
151 let res: Vec<Value> = self
152 .0
153 .into_vec()
154 .into_iter()
155 .map(Constraint::to_cbor_value)
156 .collect::<Result<_, _>>()?;
157 Ok(Value::Array(res))
158 }
159 }
160
161 /// This is Rust equivalent of `dicePolicy` in the CDDL above. Keep in sync!
162 #[derive(Clone, Debug, PartialEq)]
163 pub struct DicePolicy {
164 /// Dice policy version
165 pub version: u64,
166 /// List of `NodeConstraints`, one for each node of Dice chain.
167 pub node_constraints_list: Box<[NodeConstraints]>,
168 }
169
170 impl AsCborValue for DicePolicy {
from_cbor_value(value: Value) -> Result<Self, CoseError>171 fn from_cbor_value(value: Value) -> Result<Self, CoseError> {
172 let mut arr = value.into_array().map_err(|_| UnexpectedItem("-", "Array"))?;
173 if arr.len() < 2 {
174 return Err(UnexpectedItem("Array", "Array with at least 2 elements"));
175 }
176 let (version, node_cons_list) = (value_to_integer(arr.first().unwrap())?, arr.split_off(1));
177 let version: u64 = version.try_into().map_err(|_| UnexpectedItem("-", "u64"))?;
178 let node_cons_list: Vec<NodeConstraints> = node_cons_list
179 .into_iter()
180 .map(NodeConstraints::from_cbor_value)
181 .collect::<Result<_, _>>()?;
182 Ok(Self { version, node_constraints_list: node_cons_list.into_boxed_slice() })
183 }
184
to_cbor_value(self) -> Result<Value, CoseError>185 fn to_cbor_value(self) -> Result<Value, CoseError> {
186 let mut res: Vec<Value> = Vec::with_capacity(1 + self.node_constraints_list.len());
187 res.push(Value::from(self.version));
188 for node_cons in self.node_constraints_list.into_vec() {
189 res.push(node_cons.to_cbor_value()?)
190 }
191 Ok(Value::Array(res))
192 }
193 }
194
195 impl CborSerializable for DicePolicy {}
196
197 impl DicePolicy {
198 /// Dice chain policy verifier - Compare the input dice chain against this Dice policy.
199 /// The method returns Ok() if the dice chain meets the constraints set in Dice policy,
200 /// otherwise returns error in case of mismatch.
201 /// TODO(b/291238565) Create a separate error module for DicePolicy mismatches.
matches_dice_chain(&self, dice_chain: &[u8]) -> Result<(), Error>202 pub fn matches_dice_chain(&self, dice_chain: &[u8]) -> Result<(), Error> {
203 let dice_chain = deserialize_cbor_array(dice_chain)?;
204 check_is_explicit_key_dice_chain(&dice_chain)?;
205 if dice_chain.len() != self.node_constraints_list.len() {
206 return Err(format!(
207 "Dice chain size({}) does not match policy({})",
208 dice_chain.len(),
209 self.node_constraints_list.len()
210 ));
211 }
212
213 for (n, (dice_node, node_constraints)) in
214 zip(dice_chain, self.node_constraints_list.iter()).enumerate()
215 {
216 let dice_node_payload = if n <= 1 {
217 // 1st & 2nd dice node of Explicit-key DiceCertChain format are
218 // EXPLICIT_KEY_DICE_CERT_CHAIN_VERSION & DiceCertChainInitialPayload. The rest are
219 // DiceChainEntry which is a CoseSign1.
220 dice_node
221 } else {
222 payload_value_from_cose_sign(dice_node)
223 .map_err(|e| format!("Unable to get Cose payload at {n}: {e:?}"))?
224 };
225 check_constraints_on_node(node_constraints, &dice_node_payload)
226 .map_err(|e| format!("Mismatch found at {n}: {e:?}"))?;
227 }
228 Ok(())
229 }
230 }
231
232 /// Matches a single DICE cert chain node against the corresponding node constraints of the DICE
233 /// policy.
check_constraints_on_node( node_constraints: &NodeConstraints, dice_node: &Value, ) -> Result<(), Error>234 pub fn check_constraints_on_node(
235 node_constraints: &NodeConstraints,
236 dice_node: &Value,
237 ) -> Result<(), Error> {
238 for constraint in node_constraints.0.iter() {
239 check_constraint_on_node(constraint, dice_node)?;
240 }
241 Ok(())
242 }
243
check_constraint_on_node(constraint: &Constraint, dice_node: &Value) -> Result<(), Error>244 fn check_constraint_on_node(constraint: &Constraint, dice_node: &Value) -> Result<(), Error> {
245 let Constraint(cons_type, path, value_in_constraint) = constraint;
246 let value_in_node = lookup_in_nested_container(dice_node, path)?
247 .ok_or(format!("Value not found for constraint_path {path:?})"))?;
248 match *cons_type {
249 EXACT_MATCH_CONSTRAINT => {
250 if value_in_node != *value_in_constraint {
251 return Err(format!(
252 "Policy mismatch. Expected {value_in_constraint:?}; found {value_in_node:?}"
253 ));
254 }
255 }
256 GREATER_OR_EQUAL_CONSTRAINT => {
257 let value_in_node = value_in_node
258 .as_integer()
259 .ok_or("Mismatch type: expected a CBOR integer".to_string())?;
260 let value_min = value_in_constraint
261 .as_integer()
262 .ok_or("Mismatch type: expected a CBOR integer".to_string())?;
263 if value_in_node < value_min {
264 return Err(format!(
265 "Policy mismatch. Expected >= {value_min:?}; found {value_in_node:?}"
266 ));
267 }
268 }
269 cons_type => return Err(format!("Unexpected constraint type {cons_type:?}")),
270 };
271 Ok(())
272 }
273
274 /// Lookup value corresponding to constraint path in nested container.
275 /// This function recursively calls itself.
276 /// The depth of recursion is limited by the size of constraint_path.
lookup_in_nested_container( container: &Value, constraint_path: &[i64], ) -> Result<Option<Value>, Error>277 pub fn lookup_in_nested_container(
278 container: &Value,
279 constraint_path: &[i64],
280 ) -> Result<Option<Value>, Error> {
281 if constraint_path.is_empty() {
282 return Ok(Some(container.clone()));
283 }
284 let explicit_container = get_container_from_value(container)?;
285 lookup_value_in_container(&explicit_container, constraint_path[0])
286 .map_or_else(|| Ok(None), |val| lookup_in_nested_container(val, &constraint_path[1..]))
287 }
288
get_container_from_value(container: &Value) -> Result<Container, Error>289 fn get_container_from_value(container: &Value) -> Result<Container, Error> {
290 match container {
291 // Value can be Map/Array/Encoded Map. Encoded Arrays are not yet supported (or required).
292 // Note: Encoded Map is used for Configuration descriptor entry in DiceChainEntryPayload.
293 Value::Bytes(b) => Value::from_slice(b)
294 .map_err(|e| format!("{e:?}"))?
295 .into_map()
296 .map(|m| Container::Map(Cow::Owned(m)))
297 .map_err(|e| format!("Expected a CBOR map: {:?}", e)),
298 Value::Map(map) => Ok(Container::Map(Cow::Borrowed(map))),
299 Value::Array(array) => Ok(Container::Array(array)),
300 _ => Err(format!("Expected an array/map/bytes {container:?}")),
301 }
302 }
303
304 #[derive(Clone)]
305 enum Container<'a> {
306 Map(Cow<'a, Vec<(Value, Value)>>),
307 Array(&'a Vec<Value>),
308 }
309
lookup_value_in_container<'a>(container: &'a Container<'a>, key: i64) -> Option<&'a Value>310 fn lookup_value_in_container<'a>(container: &'a Container<'a>, key: i64) -> Option<&'a Value> {
311 match container {
312 Container::Array(array) => array.get(key as usize),
313 Container::Map(map) => {
314 let key = Value::Integer(key.into());
315 let mut val = None;
316 for (k, v) in map.iter() {
317 if k == &key {
318 val = Some(v);
319 break;
320 }
321 }
322 val
323 }
324 }
325 }
326
327 /// This library only works with Explicit-key DiceCertChain format. Further we require it to have
328 /// at least 1 DiceChainEntry. Note that this is a lightweight check so that we fail early for
329 /// legacy chains.
check_is_explicit_key_dice_chain(dice_chain: &[Value]) -> Result<(), Error>330 pub fn check_is_explicit_key_dice_chain(dice_chain: &[Value]) -> Result<(), Error> {
331 if matches!(dice_chain, [Value::Integer(_version), Value::Bytes(_public_key), _entry, ..]) {
332 Ok(())
333 } else {
334 Err("Chain is not in explicit key format".to_string())
335 }
336 }
337
338 /// Extract the payload from the COSE Sign
payload_value_from_cose_sign(cbor: Value) -> Result<Value, Error>339 pub fn payload_value_from_cose_sign(cbor: Value) -> Result<Value, Error> {
340 let sign1 = CoseSign1::from_cbor_value(cbor)
341 .map_err(|e| format!("Error extracting CoseSign1: {e:?}"))?;
342 match sign1.payload {
343 None => Err("Missing payload".to_string()),
344 Some(payload) => Value::from_slice(&payload).map_err(|e| format!("{e:?}")),
345 }
346 }
347
348 /// Decode a CBOR array
deserialize_cbor_array(cbor_array_bytes: &[u8]) -> Result<Vec<Value>, Error>349 pub fn deserialize_cbor_array(cbor_array_bytes: &[u8]) -> Result<Vec<Value>, Error> {
350 let cbor_array = Value::from_slice(cbor_array_bytes)
351 .map_err(|e| format!("Unable to decode top-level CBOR: {e:?}"))?;
352 let cbor_array =
353 cbor_array.into_array().map_err(|e| format!("Expected an array found: {e:?}"))?;
354 Ok(cbor_array)
355 }
356
357 // Useful to convert [`ciborium::Value`] to integer. Note we already downgrade the returned
358 // integer to i64 for convenience. Value::Integer is capable of storing bigger numbers.
value_to_integer(value: &Value) -> Result<i64, CoseError>359 fn value_to_integer(value: &Value) -> Result<i64, CoseError> {
360 let num = value
361 .as_integer()
362 .ok_or(CoseError::UnexpectedItem("-", "Integer"))?
363 .try_into()
364 .map_err(|_| CoseError::UnexpectedItem("Integer", "i64"))?;
365 Ok(num)
366 }
367