1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
// Copyright 2019 Contributors to the Parsec project. // SPDX-License-Identifier: Apache-2.0 //! Module for abstracting resource handle management //! //! This module presents an abstraction over the TPM functionality exposed through the core //! `Context` structure. The abstraction works by hiding resource handle management from the //! client. This is achieved by passing objects back and forth in the form of contexts. Thus, when //! an object is created, its saved context is returned and the object is flushed from the TPM. //! Whenever the client needs to use said object, it calls the desired operation with the context //! as a parameter - the context is loaded in the TPM, the operation performed and the context //! flushed out again before the result is returned. //! //! Object contexts thus act as an opaque handle that can, however, be used by the client to seralize //! and persist the underlying data. use crate::constants::*; use crate::response_code::{Error, Result, WrapperErrorKind as ErrorKind}; use crate::tss2_esys::*; use crate::utils::algorithm_specifiers::{Cipher, EllipticCurve, HashingAlgorithm}; use crate::utils::tickets::VerifiedTicket; use crate::utils::{ self, create_restricted_decryption_rsa_public, create_unrestricted_signing_ecc_public, create_unrestricted_signing_rsa_public, AsymSchemeUnion, Hierarchy, PublicIdUnion, PublicKey, TpmaSessionBuilder, TpmsContext, RSA_KEY_SIZES, }; use crate::Context; use log::error; use std::convert::{TryFrom, TryInto}; use utils::tcti::Tcti; /// Structure offering an abstracted programming experience. /// /// The `TransientKeyContext` makes use of a root key from which the other, client-controlled /// keyes are derived. /// /// Currently, only functionality necessary for RSA key creation and usage (for signing and /// verifying signatures) is implemented. More precisely, the RSA SSA asymmetric scheme with /// SHA256 is used for all created and imported keys. #[allow(clippy::module_name_repetitions)] #[derive(Debug)] pub struct TransientKeyContext { context: Context, root_key_handle: ESYS_TR, } impl TransientKeyContext { /// Create a new signing key. /// /// A key is created as a descendant of the context root key, with the given parameters. /// /// If successful, the result contains the saved context of the key and a vector of /// bytes forming the authentication value for said key. /// /// # Constraints /// * `auth_size` must be at most 32 /// /// # Errors /// * if the authentication size is larger than 32 a `WrongParamSize` wrapper error is returned /// * for RSA keys, if the specified key size is not one of 1024, 2048, 3072 or 4096, `WrongParamSize` /// is returned /// * if the asymmetric scheme is not a signing scheme, `InconsistentParams` is returned /// * errors are returned if any method calls return an error: `Context::get_random`, /// `TransientKeyContext::set_session_attrs`, `Context::create_key`, `Context::load`, /// `Context::context_save`, `Context::context_flush` pub fn create_signing_key( &mut self, key_params: KeyParams, auth_size: usize, ) -> Result<(TpmsContext, Vec<u8>)> { if auth_size > 32 { return Err(Error::local_error(ErrorKind::WrongParamSize)); } let key_auth = if auth_size > 0 { self.set_session_attrs()?; self.context.get_random(auth_size)? } else { vec![] }; self.set_session_attrs()?; let (key_priv, key_pub) = self.context.create_key( self.root_key_handle, &self.get_public_from_params(key_params)?, &key_auth, &[], &[], &[], )?; self.set_session_attrs()?; let key_handle = self.context.load(self.root_key_handle, key_priv, key_pub)?; self.set_session_attrs()?; let key_context = self.context.context_save(key_handle).or_else(|e| { self.context.flush_context(key_handle)?; Err(e) })?; self.context.flush_context(key_handle)?; Ok((key_context, key_auth)) } fn get_public_from_params(&self, params: KeyParams) -> Result<TPM2B_PUBLIC> { match params { KeyParams::Rsa { size, scheme, pub_exponent, } => { if RSA_KEY_SIZES.iter().find(|sz| **sz == size).is_none() { return Err(Error::local_error(ErrorKind::WrongParamSize)); } Ok(create_unrestricted_signing_rsa_public( scheme, size, pub_exponent, )?) } KeyParams::Ecc { curve, scheme } => { Ok(create_unrestricted_signing_ecc_public(scheme, curve)?) } } } /// Load a previously generated RSA public key. /// /// Returns the key context. /// /// # Constraints /// * `public_key` must be 128, 256, 384 or 512 bytes (i.e. slice elements) long, corresponding to 1024, 2048, 3072 or 4096 bits /// /// # Errors /// * if the public key length is different than 128, 256, 384 or 512 bytes, a `WrongParamSize` wrapper error is returned /// * errors are returned if any method calls return an error: /// `TransientKeyContext::`set_session_attrs`, `Context::load_external_public`, /// `Context::context_save`, `Context::flush_context` pub fn load_external_rsa_public_key(&mut self, public_key: &[u8]) -> Result<TpmsContext> { if RSA_KEY_SIZES .iter() .find(|sz| usize::from(**sz) == public_key.len() * 8) .is_none() { return Err(Error::local_error(ErrorKind::WrongParamSize)); } let mut pk_buffer = [0_u8; 512]; pk_buffer[..public_key.len()].clone_from_slice(&public_key[..public_key.len()]); let pk = TPMU_PUBLIC_ID { rsa: TPM2B_PUBLIC_KEY_RSA { size: public_key.len().try_into().unwrap(), // should not fail on valid targets, given the checks above buffer: pk_buffer, }, }; let mut public = create_unrestricted_signing_rsa_public( AsymSchemeUnion::RSASSA(HashingAlgorithm::Sha256), u16::try_from(public_key.len()).unwrap() * 8_u16, 0, )?; public.publicArea.unique = pk; self.set_session_attrs()?; let key_handle = self .context .load_external_public(&public, Hierarchy::Owner)?; self.set_session_attrs()?; let key_context = self.context.context_save(key_handle).or_else(|e| { self.context.flush_context(key_handle)?; Err(e) })?; self.context.flush_context(key_handle)?; Ok(key_context) } /// Read the public part from a previously generated key. /// /// The method takes the key as a parameter and returns its public part. /// /// # Errors /// * errors are returned if any method calls return an error: `Context::context_load`, /// `Context::read_public`, `Context::flush_context`, /// `TransientKeyContext::set_session_attrs` pub fn read_public_key(&mut self, key_context: TpmsContext) -> Result<PublicKey> { self.set_session_attrs()?; let key_handle = self.context.context_load(key_context)?; self.set_session_attrs()?; let key_pub_id = self.context.read_public(key_handle).or_else(|e| { self.context.flush_context(key_handle)?; Err(e) })?; let key = match unsafe { PublicIdUnion::from_public(&key_pub_id)? } { // call should be safe given our trust in the TSS library PublicIdUnion::Rsa(pub_key) => { let mut key = pub_key.buffer.to_vec(); key.truncate(pub_key.size.try_into().unwrap()); // should not fail on supported targets PublicKey::Rsa(key) } PublicIdUnion::Ecc(pub_key) => { let mut x = pub_key.x.buffer.to_vec(); x.truncate(pub_key.x.size.try_into().unwrap()); // should not fail on supported targets let mut y = pub_key.y.buffer.to_vec(); y.truncate(pub_key.y.size.try_into().unwrap()); // should not fail on supported targets PublicKey::Ecc { x, y } } _ => return Err(Error::local_error(ErrorKind::UnsupportedParam)), }; self.context.flush_context(key_handle)?; Ok(key) } /// Sign a digest with an existing key. /// /// Takes the key as a parameter, signs and returns the signature. /// /// # Errors /// * errors are returned if any method calls return an error: `Context::context_load`, /// `Context::sign`, `Context::flush_context`, `TransientKeyContext::set_session_attrs` /// `Context::set_handle_auth` pub fn sign( &mut self, key_context: TpmsContext, key_auth: &[u8], digest: &[u8], ) -> Result<utils::Signature> { self.set_session_attrs()?; let key_handle = self.context.context_load(key_context)?; self.context .tr_set_auth(key_handle, key_auth) .or_else(|e| { self.context.flush_context(key_handle)?; Err(e) })?; let scheme = TPMT_SIG_SCHEME { scheme: TPM2_ALG_NULL, details: Default::default(), }; let validation = TPMT_TK_HASHCHECK { tag: TPM2_ST_HASHCHECK, hierarchy: TPM2_RH_NULL, digest: Default::default(), }; self.set_session_attrs()?; let signature = self .context .sign(key_handle, digest, scheme, &validation) .or_else(|e| { self.context.flush_context(key_handle)?; Err(e) })?; self.context.flush_context(key_handle)?; Ok(signature) } /// Verify a signature against a digest. /// /// Given a digest, a key and a signature, this method returns a `Verified` ticket if the /// verification was successful. /// /// # Errors /// * if the verification fails (i.e. the signature is invalid), a TPM error is returned /// * errors are returned if any method calls return an error: `Context::context_load`, /// `Context::verify_signature`, `Context::flush_context`, /// `TransientKeyContext::set_session_attrs` pub fn verify_signature( &mut self, key_context: TpmsContext, digest: &[u8], signature: utils::Signature, ) -> Result<VerifiedTicket> { self.set_session_attrs()?; let key_handle = self.context.context_load(key_context)?; let signature: TPMT_SIGNATURE = signature.try_into().or_else(|e| { self.context.flush_context(key_handle)?; Err(e) })?; self.set_session_attrs()?; let verified = self .context .verify_signature(key_handle, digest, &signature) .or_else(|e| { self.context.flush_context(key_handle)?; Err(e) })?; self.context.flush_context(key_handle)?; Ok(verified.try_into()?) } /// Sets the encrypt and decrypt flags on the main session used by the context. /// /// # Errors /// * if `Context::set_session_attr` returns an error, that error is propagated through fn set_session_attrs(&mut self) -> Result<()> { let (session, _, _) = self.context.sessions(); let session_attr = utils::TpmaSessionBuilder::new() .with_flag(TPMA_SESSION_DECRYPT) .with_flag(TPMA_SESSION_ENCRYPT) .build(); self.context.tr_sess_set_attributes(session, session_attr)?; Ok(()) } } /// Build a new `TransientKeyContext`. /// /// # Default values /// * TCTI: Device TCTI /// * Hierarchy: Owner hierarchy /// * Root key size: 2048 bits /// * Root key authentication size: 32 bytes /// * Hierarchy authentication value: Empty array of bytes /// * Session encryption cipher: 256 bit AES in CFB mode /// * Session hash algorithm: SHA256 #[derive(Debug)] pub struct TransientKeyContextBuilder { tcti: Tcti, hierarchy: Hierarchy, root_key_size: u16, // TODO: replace with root key PUBLIC definition root_key_auth_size: usize, hierarchy_auth: Vec<u8>, default_context_cipher: Cipher, session_hash_alg: TPM2_ALG_ID, // TODO: Create Rust-native version } impl TransientKeyContextBuilder { /// Create a new builder. pub fn new() -> Self { TransientKeyContextBuilder { tcti: Tcti::Device(Default::default()), hierarchy: Hierarchy::Owner, root_key_size: 2048, root_key_auth_size: 32, hierarchy_auth: Vec::new(), default_context_cipher: Cipher::aes_256_cfb(), session_hash_alg: TPM2_ALG_SHA256, } } /// Define the TCTI to be used by the client. pub fn with_tcti(mut self, tcti: Tcti) -> Self { self.tcti = tcti; self } /// Define which hierarchy will be used for the keys being managed. pub fn with_hierarchy(mut self, hierarchy: Hierarchy) -> Self { self.hierarchy = hierarchy; self } /// Choose length in bits of primary key that will serve as parent to all user keys. pub fn with_root_key_size(mut self, root_key_size: u16) -> Self { self.root_key_size = root_key_size; self } /// Choose authentication value length (in bytes) for primary key. pub fn with_root_key_auth_size(mut self, root_key_auth_size: usize) -> Self { self.root_key_auth_size = root_key_auth_size; self } /// Input the authentication value of the working hierarchy. pub fn with_hierarchy_auth(mut self, hierarchy_auth: Vec<u8>) -> Self { self.hierarchy_auth = hierarchy_auth; self } /// Define the cipher to be used within this context as a default. /// /// Currently this default is used for: /// * securing command parameters using session-based encryption /// * encrypting all user keys using the primary key pub fn with_default_context_cipher(mut self, default_context_cipher: Cipher) -> Self { self.default_context_cipher = default_context_cipher; self } /// Define the cipher to be used by sessions for hashing commands. pub fn with_session_hash_alg(mut self, session_hash_alg: TPM2_ALG_ID) -> Self { self.session_hash_alg = session_hash_alg; self } /// Bootstrap the TransientKeyContext. /// /// The root key is created as a primary key in the provided hierarchy and thus authentication is /// needed for said hierarchy. The authentication valuei for the key is generated by the TPM itself, /// with a configurable length, and never exposed outside the context. /// /// # Safety /// * it is the responsibility of the client to ensure that the context can be initialized /// safely, threading-wise /// * the client is also responsible of choosing the correct TCTI to connect to. /// * it is the responsability of the client to set a sufficiently secure default cipher for the context /// /// # Constraints /// * `root_key_size` must be 1024, 2048, 3072 or 4096 /// * `root_key_auth_size` must be at most 32 /// /// # Errors /// * errors are returned if any method calls return an error: `Context::get_random`, /// `Context::start_auth_session`, `Context::create_primary_key`, `Context::flush_context`, /// `Context::set_handle_auth` /// * if the root key authentication size is given greater than 32 or if the root key size is /// not 1024, 2048, 3072 or 4096, a `WrongParamSize` wrapper error is returned pub unsafe fn build(self) -> Result<TransientKeyContext> { if self.root_key_auth_size > 32 { return Err(Error::local_error(ErrorKind::WrongParamSize)); } if RSA_KEY_SIZES .iter() .find(|sz| **sz == self.root_key_size) .is_none() { error!("The reference implementation only supports key sizes of 1,024 and 2,048 bits."); return Err(Error::local_error(ErrorKind::WrongParamSize)); } let mut context = Context::new(self.tcti)?; let session = context.start_auth_session( ESYS_TR_NONE, ESYS_TR_NONE, &[], TPM2_SE_HMAC, self.default_context_cipher.into(), self.session_hash_alg, )?; let session_attr = TpmaSessionBuilder::new() .with_flag(TPMA_SESSION_DECRYPT) .with_flag(TPMA_SESSION_ENCRYPT) .build(); context.tr_sess_set_attributes(session, session_attr)?; context.set_sessions((session, ESYS_TR_NONE, ESYS_TR_NONE)); let root_key_auth: Vec<u8> = if self.root_key_auth_size > 0 { context.get_random(self.root_key_auth_size)? } else { vec![] }; if !self.hierarchy_auth.is_empty() { context.tr_set_auth(self.hierarchy.esys_rh(), &self.hierarchy_auth)?; } let root_key_handle = context.create_primary_key( self.hierarchy.esys_rh(), &create_restricted_decryption_rsa_public( self.default_context_cipher, self.root_key_size, 0, )?, &root_key_auth, &[], &[], &[], )?; let new_session = context.start_auth_session( root_key_handle, ESYS_TR_NONE, &[], TPM2_SE_HMAC, self.default_context_cipher.into(), self.session_hash_alg, )?; let (old_session, _, _) = context.sessions(); context.set_sessions((new_session, ESYS_TR_NONE, ESYS_TR_NONE)); context.flush_context(old_session)?; Ok(TransientKeyContext { context, root_key_handle, }) } } impl Default for TransientKeyContextBuilder { fn default() -> Self { TransientKeyContextBuilder::new() } } /// Parameters for the kinds of keys supported by the context #[derive(Debug, Clone, Copy)] pub enum KeyParams { Rsa { /// Size of key in bits /// /// Can only be one of: 1024, 2048, 3072 or 4096 size: u16, /// Asymmetric scheme to be used with the key /// /// *Must* be an RSA-specific scheme scheme: AsymSchemeUnion, /// Public exponent of the key /// /// If set to 0, it will default to 2^16 - 1 pub_exponent: u32, }, Ecc { /// Curve that the key will be based on curve: EllipticCurve, /// Asymmetric scheme to be used with the key /// /// *Must* be an ECC scheme scheme: AsymSchemeUnion, }, }