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
// Copyright 2021 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
use crate::{
Context, Result, ReturnCode,
context::handle_manager::HandleDropAction,
handles::{AuthHandle, KeyHandle, ObjectHandle},
interface_types::{
YesNo,
algorithm::HashingAlgorithm,
reserved_handles::{Enables, Hierarchy, HierarchyAuth},
},
structures::{
Auth, CreatePrimaryKeyResult, CreationData, CreationTicket, Data, Digest, PcrSelectionList,
Public, SensitiveCreate, SensitiveData,
},
tss2_esys::{
Esys_ChangeEPS, Esys_ChangePPS, Esys_Clear, Esys_ClearControl, Esys_CreatePrimary,
Esys_HierarchyChangeAuth, Esys_HierarchyControl, Esys_SetPrimaryPolicy,
},
};
use log::error;
use std::convert::{TryFrom, TryInto};
use std::ptr::null_mut;
impl Context {
/// Create a primary key and return the handle.
///
/// The authentication value, initial data, outside info and creation PCRs are passed as slices
/// which are then converted by the method into TSS native structures.
///
/// # Errors
/// * if either of the slices is larger than the maximum size of the native objects, a
/// `WrongParamSize` wrapper error is returned
// TODO: Fix when compacting the arguments into a struct
#[allow(clippy::too_many_arguments)]
pub fn create_primary(
&mut self,
primary_handle: Hierarchy,
public: Public,
auth_value: Option<Auth>,
initial_data: Option<SensitiveData>,
outside_info: Option<Data>,
creation_pcrs: Option<PcrSelectionList>,
) -> Result<CreatePrimaryKeyResult> {
let sensitive_create = SensitiveCreate::new(
auth_value.unwrap_or_default(),
initial_data.unwrap_or_default(),
);
let creation_pcrs = PcrSelectionList::list_from_option(creation_pcrs);
let mut out_public_ptr = null_mut();
let mut creation_data_ptr = null_mut();
let mut creation_hash_ptr = null_mut();
let mut creation_ticket_ptr = null_mut();
let mut object_handle = ObjectHandle::None.into();
ReturnCode::ensure_success(
unsafe {
Esys_CreatePrimary(
self.mut_context(),
ObjectHandle::from(primary_handle).into(),
self.required_session_1()?,
self.optional_session_2(),
self.optional_session_3(),
&sensitive_create.try_into()?,
&public.try_into()?,
&outside_info.unwrap_or_default().into(),
&creation_pcrs.into(),
&mut object_handle,
&mut out_public_ptr,
&mut creation_data_ptr,
&mut creation_hash_ptr,
&mut creation_ticket_ptr,
)
},
|ret| {
error!("Error in creating primary key: {:#010X}", ret);
},
)?;
let out_public_owned = Context::ffi_data_to_owned(out_public_ptr)?;
let creation_data_owned = Context::ffi_data_to_owned(creation_data_ptr)?;
let creation_hash_owned = Context::ffi_data_to_owned(creation_hash_ptr)?;
let creation_ticket_owned = Context::ffi_data_to_owned(creation_ticket_ptr)?;
let primary_key_handle = KeyHandle::from(object_handle);
self.handle_manager
.add_handle(primary_key_handle.into(), HandleDropAction::Flush)?;
Ok(CreatePrimaryKeyResult {
key_handle: primary_key_handle,
out_public: Public::try_from(out_public_owned)?,
creation_data: CreationData::try_from(creation_data_owned)?,
creation_hash: Digest::try_from(creation_hash_owned)?,
creation_ticket: CreationTicket::try_from(creation_ticket_owned)?,
})
}
/// Enables or disables use of a hierarchy.
///
/// # Arguments
///
/// * `enable` - The hierarchy or associated NV storage whose state will be changed.
/// * `state` - `true` to enable use of the hierarchy, or `false` to disable it.
///
/// # Details
///
/// *From the specification*
/// > This command enables and disables use of a hierarchy and its associated NV storage. The
/// > command allows phEnable, phEnableNV, shEnable, and ehEnable to be changed when the proper
/// > authorization is provided.
///
/// # Example
///
/// ```rust
/// # use tss_esapi::{Context, TctiNameConf};
/// # use tss_esapi::interface_types::{
/// # reserved_handles::Enables, session_handles::AuthSession,
/// # };
/// # let mut context = Context::new(
/// # TctiNameConf::from_environment_variable().expect("Failed to get TCTI"),
/// # ).expect("Failed to create Context");
/// context
/// .execute_with_session(Some(AuthSession::Password), |ctx| {
/// ctx.hierarchy_control(Enables::Endorsement, false)?;
/// ctx.hierarchy_control(Enables::Endorsement, true)
/// })
/// .unwrap();
/// ```
pub fn hierarchy_control(&mut self, enable: Enables, state: bool) -> Result<()> {
ReturnCode::ensure_success(
unsafe {
Esys_HierarchyControl(
self.mut_context(),
ObjectHandle::Platform.into(),
self.required_session_1()?,
self.optional_session_2(),
self.optional_session_3(),
ObjectHandle::from(enable).into(),
YesNo::from(state).into(),
)
},
|ret| {
error!("Error controlling hierarchy: {:#010X}", ret);
},
)
}
/// Sets the authorization policy for a hierarchy.
///
/// # Arguments
///
/// * `auth_handle` - The hierarchy whose authorization policy will be changed.
/// * `auth_policy` - The new authorization policy digest.
/// * `hash_algorithm` - The hash algorithm used to compute `auth_policy`. An empty policy must
/// be paired with [`HashingAlgorithm::Null`].
///
/// # Details
///
/// *From the specification*
/// > This command allows setting of the authorization policy for the lockout (lockoutPolicy),
/// > the platform hierarchy (platformPolicy), the storage hierarchy (ownerPolicy), and the
/// > endorsement hierarchy (endorsementPolicy).
///
/// # Example
///
/// ```rust
/// # use tss_esapi::{Context, TctiNameConf};
/// # use tss_esapi::{
/// # interface_types::{algorithm::HashingAlgorithm, reserved_handles::HierarchyAuth,
/// # session_handles::AuthSession},
/// # structures::Digest,
/// # };
/// # let mut context = Context::new(
/// # TctiNameConf::from_environment_variable().expect("Failed to get TCTI"),
/// # ).expect("Failed to create Context");
/// context
/// .execute_with_session(Some(AuthSession::Password), |ctx| {
/// ctx.set_primary_policy(
/// HierarchyAuth::Platform,
/// Digest::default(),
/// HashingAlgorithm::Null,
/// )
/// })
/// .unwrap();
/// ```
pub fn set_primary_policy(
&mut self,
auth_handle: HierarchyAuth,
auth_policy: Digest,
hash_algorithm: HashingAlgorithm,
) -> Result<()> {
ReturnCode::ensure_success(
unsafe {
Esys_SetPrimaryPolicy(
self.mut_context(),
ObjectHandle::from(auth_handle).into(),
self.required_session_1()?,
self.optional_session_2(),
self.optional_session_3(),
&auth_policy.into(),
hash_algorithm.into(),
)
},
|ret| {
error!("Error setting primary policy: {:#010X}", ret);
},
)
}
/// Replaces the platform primary seed with a new random value.
///
/// # Arguments
///
/// This command has no command-specific arguments. The first configured session must authorize
/// the platform hierarchy.
///
/// # Details
///
/// *From the specification*
/// > This replaces the current platform primary seed (PPS) with a value from the RNG and sets
/// > platformPolicy to the default initialization value (the Empty Buffer).
///
/// Existing objects in the platform hierarchy can no longer be loaded after this command.
///
/// # Example
///
/// ```rust
/// # use tss_esapi::{Context, TctiNameConf};
/// # use tss_esapi::interface_types::session_handles::AuthSession;
/// # let mut context = Context::new(
/// # TctiNameConf::from_environment_variable().expect("Failed to get TCTI"),
/// # ).expect("Failed to create Context");
/// context
/// .execute_with_session(Some(AuthSession::Password), |ctx| ctx.change_pps())
/// .unwrap();
/// ```
pub fn change_pps(&mut self) -> Result<()> {
ReturnCode::ensure_success(
unsafe {
Esys_ChangePPS(
self.mut_context(),
ObjectHandle::Platform.into(),
self.required_session_1()?,
self.optional_session_2(),
self.optional_session_3(),
)
},
|ret| {
error!("Error changing platform primary seed: {:#010X}", ret);
},
)
}
/// Replaces the endorsement primary seed with a new random value.
///
/// # Arguments
///
/// This command has no command-specific arguments. The first configured session must authorize
/// the platform hierarchy.
///
/// # Details
///
/// *From the specification*
/// > This replaces the current endorsement primary seed (EPS) with a value from the RNG and
/// > sets the Endorsement hierarchy controls to their default initialization values: ehEnable
/// > is SET, endorsementAuth and endorsementPolicy are both set to the Empty Buffer. It will
/// > flush any resident objects (transient or persistent) in the Endorsement hierarchy and not
/// > allow objects in the hierarchy associated with the previous EPS to be loaded.
///
/// Existing objects in the endorsement hierarchy can no longer be loaded after this command.
///
/// # Example
///
/// ```rust
/// # use tss_esapi::{Context, TctiNameConf};
/// # use tss_esapi::interface_types::session_handles::AuthSession;
/// # let mut context = Context::new(
/// # TctiNameConf::from_environment_variable().expect("Failed to get TCTI"),
/// # ).expect("Failed to create Context");
/// context
/// .execute_with_session(Some(AuthSession::Password), |ctx| ctx.change_eps())
/// .unwrap();
/// ```
pub fn change_eps(&mut self) -> Result<()> {
ReturnCode::ensure_success(
unsafe {
Esys_ChangeEPS(
self.mut_context(),
ObjectHandle::Platform.into(),
self.required_session_1()?,
self.optional_session_2(),
self.optional_session_3(),
)
},
|ret| {
error!("Error changing endorsement primary seed: {:#010X}", ret);
},
)
}
/// Clear all TPM context associated with a specific Owner
pub fn clear(&mut self, auth_handle: AuthHandle) -> Result<()> {
ReturnCode::ensure_success(
unsafe {
Esys_Clear(
self.mut_context(),
auth_handle.into(),
self.required_session_1()?,
self.optional_session_2(),
self.optional_session_3(),
)
},
|ret| {
error!("Error in clearing TPM hierarchy: {:#010X}", ret);
},
)
}
/// Disable or enable the TPM2_CLEAR command
pub fn clear_control(&mut self, auth_handle: AuthHandle, disable: bool) -> Result<()> {
ReturnCode::ensure_success(
unsafe {
Esys_ClearControl(
self.mut_context(),
auth_handle.into(),
self.required_session_1()?,
self.optional_session_2(),
self.optional_session_3(),
YesNo::from(disable).into(),
)
},
|ret| {
error!("Error in controlling clear command: {:#010X}", ret);
},
)
}
/// Change authorization for a hierarchy root
pub fn hierarchy_change_auth(&mut self, auth_handle: AuthHandle, new_auth: Auth) -> Result<()> {
ReturnCode::ensure_success(
unsafe {
Esys_HierarchyChangeAuth(
self.mut_context(),
auth_handle.into(),
self.required_session_1()?,
self.optional_session_2(),
self.optional_session_3(),
&new_auth.into(),
)
},
|ret| {
error!("Error changing hierarchy auth: {:#010X}", ret);
},
)
}
}