Skip to content

Commit 655714a

Browse files
committed
Improved parameter validation for the 'create_nv()' function.
1 parent 8184b7d commit 655714a

5 files changed

Lines changed: 22 additions & 13 deletions

File tree

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/).
1414
### Changed
1515

1616
- Docker images used for testing/building have been updated to the latest version.
17+
- The parameter validation for the function `create_nv()` has been improved.
1718

1819
## [0.12.2] - 2026-03-03
1920

src/context.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -355,24 +355,30 @@ impl FapiContext {
355355

356356
/// This command creates an NV index in the TPM using a given path and type.
357357
///
358+
/// If the size of the NV index is specified *implicitly* by the `nvi_type` parameter, then the `nvi_size` parameter **must** be `None`; otherwise, the `nvi_size` parameter **must** be `Some(size)` with a `size` that is greater than zero.
359+
///
358360
/// *See also:* [`Fapi_CreateNv()`](https://tpm2-tss.readthedocs.io/en/stable/group___fapi___create_nv.html)
359361
pub fn create_nv(
360362
&mut self,
361363
nv_path: &str,
362364
nvi_type: Option<&[NvFlags]>,
363-
nvi_size: usize,
365+
nvi_size: Option<NonZeroUsize>,
364366
pol_path: Option<&str>,
365367
auth_val: Option<&str>,
366368
) -> Result<(), ErrorCode> {
367369
fail_if_opt_empty!(nvi_type);
370+
if nvi_type.is_some_and(|flags| flags.iter().any(|&flag| matches!(flag, NvFlags::BitField | NvFlags::Counter | NvFlags::PCR))) != nvi_size.is_none() {
371+
return Err(ERR_INVALID_ARGUMENTS);
372+
}
368373

369374
let cstr_path = CStringHolder::try_from(nv_path)?;
370375
let cstr_type = CStringHolder::try_from(Flags::as_string(nvi_type)?)?;
371376
let cstr_poli = CStringHolder::try_from(pol_path)?;
372377
let cstr_auth = CStringHolder::try_from(auth_val)?;
378+
let nvi_bytes = nvi_size.map(NonZeroUsize::get).unwrap_or(0usize);
373379

374380
self.fapi_call(false, |context| unsafe {
375-
fapi_sys::Fapi_CreateNv(context, cstr_path.as_ptr(), cstr_type.as_ptr(), nvi_size, cstr_poli.as_ptr(), cstr_auth.as_ptr())
381+
fapi_sys::Fapi_CreateNv(context, cstr_path.as_ptr(), cstr_type.as_ptr(), nvi_bytes, cstr_poli.as_ptr(), cstr_auth.as_ptr())
376382
})
377383
}
378384

@@ -711,7 +717,7 @@ impl FapiContext {
711717

712718
/// Creates a sealed object and stores it in the FAPI metadata store.
713719
///
714-
/// The [`data`](crate::SealData) to be sealed can be given as a *non-empty* `&[u8]` slice. Alternatively, a [`NoneZeroUsize`](std::num::NonZeroUsize) size can be specified.
720+
/// The [`data`](crate::SealedData) to be sealed can be given as a *non-empty* `&[u8]` slice. Alternatively, a [`NoneZeroUsize`](std::num::NonZeroUsize) size can be specified.
715721
///
716722
/// If **no** explicit data is provided (i.e., only the size), the TPM generates random data to fill the sealed object.
717723
///

src/flags.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ impl Flags for KeyFlags {
8383

8484
/// NV index creation flags, as used by the [`create_nv()`](crate::FapiContext::create_nv) function.
8585
///
86-
/// *Note:* The Flags [`BitField`](NvFlags::BitField), [`Counter`](NvFlags::Counter) and [`PCR`](NvFlags::PCR) are mutually exclusive! If **no** type flag is given, an "ordinary" NV index is created.
86+
/// *Note:* The type flags [`BitField`](NvFlags::BitField), [`Counter`](NvFlags::Counter) and [`PCR`](NvFlags::PCR) are mutually exclusive! If one of these flags is given, then the size of the NV index is *implicit* defined; otherwise, if **no** type flag is given, an "ordinary" NV index of application-defined size is created.
8787
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
8888
#[non_exhaustive]
8989
pub enum NvFlags {
@@ -114,7 +114,7 @@ impl Flags for NvFlags {
114114
}
115115

116116
fn validate_set(flags: &BTreeSet<Self>) -> bool {
117-
flags.iter().copied().filter(|flag| matches!(*flag, Self::BitField | Self::Counter | Self::PCR)).count() < 2usize
117+
flags.iter().copied().filter(|&flag| matches!(flag, Self::BitField | Self::Counter | Self::PCR)).count() < 2usize
118118
}
119119
}
120120

tests/08_nv_test.rs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66

77
pub mod common;
88

9+
use std::num::NonZeroUsize;
10+
911
use common::{
1012
callback::MyCallbacks,
1113
param::PASSWORD,
@@ -50,7 +52,7 @@ fn test_nv_write() {
5052
tpm_initialize!(context, PASSWORD, MyCallbacks::new(PASSWORD, None));
5153

5254
// Create NV index, if not already created
53-
match context.create_nv(nv_path, Some(NV_ORDINARY_FLAGS), data.len(), None, None) {
55+
match context.create_nv(nv_path, Some(NV_ORDINARY_FLAGS), NonZeroUsize::new(data.len()), None, None) {
5456
Ok(_) => debug!("NV index created."),
5557
Err(error) => panic!("NV index creation has failed: {:?}", error),
5658
}
@@ -96,7 +98,7 @@ fn test_nv_read() {
9698
tpm_initialize!(context, PASSWORD, MyCallbacks::new(PASSWORD, None));
9799

98100
// Create NV index, if not already created
99-
match context.create_nv(nv_path, Some(NV_ORDINARY_FLAGS), data.len(), None, None) {
101+
match context.create_nv(nv_path, Some(NV_ORDINARY_FLAGS), NonZeroUsize::new(data.len()), None, None) {
100102
Ok(_) => debug!("NV index created."),
101103
Err(error) => panic!("NV index creation has failed: {:?}", error),
102104
}
@@ -142,7 +144,7 @@ fn test_nv_counter() {
142144
tpm_initialize!(context, PASSWORD, MyCallbacks::new(PASSWORD, None));
143145

144146
// Create NV index, if not already created
145-
match context.create_nv(nv_path, Some(NV_COUNTER_FLAGS), 0usize, None, None) {
147+
match context.create_nv(nv_path, Some(NV_COUNTER_FLAGS), None, None, None) {
146148
Ok(_) => debug!("NV index created."),
147149
Err(error) => panic!("NV index creation has failed: {:?}", error),
148150
}
@@ -200,7 +202,7 @@ fn test_nv_bitset() {
200202
tpm_initialize!(context, PASSWORD, MyCallbacks::new(PASSWORD, None));
201203

202204
// Create NV index, if not already created
203-
match context.create_nv(nv_path, Some(NV_BITFIELD_FLAGS), 0usize, None, None) {
205+
match context.create_nv(nv_path, Some(NV_BITFIELD_FLAGS), None, None, None) {
204206
Ok(_) => debug!("NV index created."),
205207
Err(error) => panic!("NV index creation has failed: {:?}", error),
206208
}
@@ -275,7 +277,7 @@ fn test_nv_pcr() {
275277
tpm_initialize!(context, PASSWORD, MyCallbacks::new(PASSWORD, None));
276278

277279
// Create NV index, if not already created
278-
match context.create_nv(nv_path, Some(NV_PCR_FLAGS), 0usize, None, None) {
280+
match context.create_nv(nv_path, Some(NV_PCR_FLAGS), None, None, None) {
279281
Ok(_) => debug!("NV index created."),
280282
Err(error) => panic!("NV index creation has failed: {:?}", error),
281283
}

tests/09_policy_test.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,11 @@ use rand::SeedableRng;
2020
use rand_chacha::ChaChaRng;
2121
use serial_test::serial;
2222
use sha2::{Digest, Sha256};
23-
use std::{fs, path::Path};
23+
use std::{fs, num::NonZeroUsize, path::Path};
2424
use tss2_fapi_rs::{FapiCallbacks, FapiContext, ImportData, KeyFlags, json::JsonValue};
2525

2626
const KEY_FLAGS_SIGN: &[KeyFlags] = &[KeyFlags::NoDA, KeyFlags::Sign];
27-
const POLICY_NV_AUTH_SIZE: usize = 34usize;
27+
const POLICY_NV_AUTH_SIZE: NonZeroUsize = NonZeroUsize::new(34usize).unwrap();
2828

2929
// ==========================================================================
3030
// Test cases
@@ -285,7 +285,7 @@ fn test_write_authorize_nv() {
285285
};
286286

287287
// Create NV index, if not already created
288-
match context.create_nv(nv_path, Some(&[tss2_fapi_rs::NvFlags::NoDA]), POLICY_NV_AUTH_SIZE, None, None) {
288+
match context.create_nv(nv_path, Some(&[tss2_fapi_rs::NvFlags::NoDA]), Some(POLICY_NV_AUTH_SIZE), None, None) {
289289
Ok(_) => debug!("NV index created."),
290290
Err(error) => panic!("NV index creation has failed: {:?}", error),
291291
}

0 commit comments

Comments
 (0)