Skip to content

Commit 922dc09

Browse files
committed
cleanup
1 parent d0d222e commit 922dc09

11 files changed

Lines changed: 137 additions & 173 deletions

File tree

Cargo.lock

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

benches/data

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
../examples/data

benches/fapi_benchmark.rs

Lines changed: 99 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,9 @@
44
* All rights reserved.
55
**********************************************************************************************/
66

7-
use criterion::{BenchmarkGroup, Criterion, SamplingMode, criterion_group, criterion_main, measurement::Measurement};
7+
use criterion::{criterion_group, criterion_main};
88
use rand::{Rng, rng};
9-
use std::{
10-
env,
11-
hint::black_box,
12-
num::NonZeroUsize,
13-
sync::{
14-
Once,
15-
atomic::{AtomicUsize, Ordering},
16-
},
17-
time::Duration,
18-
};
9+
use std::{env, sync::Once};
1910
use uuid::Uuid;
2011

2112
use tss2_fapi_rs::{BaseErrorCode, ErrorCode, FapiContext, KeyFlags};
@@ -27,85 +18,113 @@ use tss2_fapi_rs::{BaseErrorCode, ErrorCode, FapiContext, KeyFlags};
2718
const FLAGS_STORAGE: [KeyFlags; 3usize] = [KeyFlags::Decrypt, KeyFlags::Restricted, KeyFlags::NoDA];
2819
const FLAGS_SIGNING: [KeyFlags; 2usize] = [KeyFlags::Sign, KeyFlags::NoDA];
2920

30-
/// Benchmark #1: Get random
31-
/// ------------------------
32-
/// This benchmark measures the performance of the [`FapiContext::get_random()`] function.
33-
fn bench_get_random<M: Measurement>(group: &mut BenchmarkGroup<M>) {
34-
// Initialize TPM
35-
let mut manager = TpmManager::new();
21+
mod bench_fapi {
22+
use super::{FLAGS_SIGNING, FapiContext, TpmManager};
23+
use criterion::{BenchmarkGroup, Criterion, SamplingMode, measurement::Measurement};
24+
use std::{
25+
hint::black_box,
26+
num::NonZeroUsize,
27+
sync::atomic::{AtomicUsize, Ordering},
28+
time::Duration,
29+
};
30+
31+
/// Benchmark #1: Get random
32+
/// ------------------------
33+
/// This benchmark measures the performance of the [`FapiContext::get_random()`] function.
34+
fn get_random<M: Measurement>(group: &mut BenchmarkGroup<M>) {
35+
// Initialize TPM
36+
let mut manager = TpmManager::new();
37+
38+
// Measurement!
39+
let counter: AtomicUsize = AtomicUsize::new(0usize);
40+
group.bench_function("get_random", |b| b.iter(|| _get_random(&mut manager.0, black_box(counter.fetch_add(1usize, Ordering::Relaxed)))));
41+
}
3642

37-
// Measurement!
38-
let counter: AtomicUsize = AtomicUsize::new(0usize);
39-
group.bench_function("get_random", |b| b.iter(|| _get_random(&mut manager.0, black_box(counter.fetch_add(1usize, Ordering::Relaxed)))));
40-
}
43+
fn _get_random(context: &mut FapiContext, _n: usize) {
44+
let length = unsafe { NonZeroUsize::new(32usize).unwrap_unchecked() };
45+
let _buffer = black_box(context.get_random(length).expect("Failed to get random data!"));
46+
}
4147

42-
fn _get_random(context: &mut FapiContext, _n: usize) {
43-
let length = unsafe { NonZeroUsize::new(32usize).unwrap_unchecked() };
44-
let _buffer = black_box(context.get_random(length).expect("Failed to get random data!"));
45-
}
48+
/// Benchmark #2: Create key
49+
/// ------------------------
50+
/// This benchmark measures the performance of the [`FapiContext::create_key()`] function.
51+
fn create_key<M: Measurement>(group: &mut BenchmarkGroup<M>) {
52+
// Initialize TPM
53+
let mut manager = TpmManager::new();
4654

47-
/// Benchmark #2: Create key
48-
/// ------------------------
49-
/// This benchmark measures the performance of the [`FapiContext::create_key()`] function.
50-
fn bench_create_key<M: Measurement>(group: &mut BenchmarkGroup<M>) {
51-
// Initialize TPM
52-
let mut manager = TpmManager::new();
55+
// Measurement!
56+
let counter: AtomicUsize = AtomicUsize::new(0usize);
57+
group.bench_function("create_key", |b| b.iter(|| _create_key(&mut manager.0, &manager.1, black_box(counter.fetch_add(1usize, Ordering::Relaxed)))));
58+
}
5359

54-
// Measurement!
55-
let counter: AtomicUsize = AtomicUsize::new(0usize);
56-
group.bench_function("create_key", |b| b.iter(|| _create_key(&mut manager.0, &manager.1, black_box(counter.fetch_add(1usize, Ordering::Relaxed)))));
57-
}
60+
fn _create_key(context: &mut FapiContext, parent_path: &str, n: usize) {
61+
context.create_key(&format!("{}/key_{}", parent_path, n), Some(&FLAGS_SIGNING), None, None).expect("Failed to create key!")
62+
}
5863

59-
fn _create_key(context: &mut FapiContext, parent_path: &str, n: usize) {
60-
context.create_key(&format!("{}/key_{}", parent_path, n), Some(&FLAGS_SIGNING), None, None).expect("Failed to create key!")
61-
}
64+
/// Benchmark #3: Sign
65+
/// ------------------
66+
/// This benchmark measures the performance of the [`FapiContext::sign()`] function.
67+
fn sign<M: Measurement>(group: &mut BenchmarkGroup<M>) {
68+
// Initialize TPM
69+
let mut manager = TpmManager::new();
6270

63-
/// Benchmark #3: Sign
64-
/// ------------------
65-
/// This benchmark measures the performance of the [`FapiContext::sign()`] function.
66-
fn bench_sign<M: Measurement>(group: &mut BenchmarkGroup<M>) {
67-
// Initialize TPM
68-
let mut manager = TpmManager::new();
71+
// Create siging key
72+
let sign_key_path = format!("{}/sign_key", &manager.1);
73+
manager.0.create_key(&sign_key_path, Some(&FLAGS_SIGNING), None, None).expect("Failed to create sign key!");
6974

70-
// Create siging key
71-
let sign_key_path = format!("{}/sign_key", &manager.1);
72-
manager.0.create_key(&sign_key_path, Some(&FLAGS_SIGNING), None, None).expect("Failed to create sign key!");
75+
// Measurement!
76+
let counter: AtomicUsize = AtomicUsize::new(0usize);
77+
group.bench_function("sign", |b| b.iter(|| _sign(&mut manager.0, &sign_key_path, black_box(counter.fetch_add(1usize, Ordering::Relaxed)))));
78+
}
7379

74-
// Measurement!
75-
let counter: AtomicUsize = AtomicUsize::new(0usize);
76-
group.bench_function("sign", |b| b.iter(|| _sign(&mut manager.0, &sign_key_path, black_box(counter.fetch_add(1usize, Ordering::Relaxed)))));
77-
}
80+
fn _sign(context: &mut FapiContext, sign_key_path: &str, n: usize) {
81+
let mut digest = [0u8; 32usize];
82+
digest[..size_of::<usize>()].copy_from_slice(&n.to_be_bytes());
83+
let _signature = black_box(context.sign(sign_key_path, None, &digest, false, false).expect("Failed to sign message!"));
84+
}
7885

79-
fn _sign(context: &mut FapiContext, sign_key_path: &str, n: usize) {
80-
let mut digest = [0u8; 32usize];
81-
digest[..size_of::<usize>()].copy_from_slice(&n.to_be_bytes());
82-
let _signature = black_box(context.sign(sign_key_path, None, &digest, false, false).expect("Failed to sign message!"));
83-
}
86+
/// Benchmark #4: Verify signature
87+
/// ------------------------------
88+
/// This benchmark measures the performance of the [`FapiContext::verify_signature()`] function.
89+
fn verify_signature<M: Measurement>(group: &mut BenchmarkGroup<M>) {
90+
// Initialize TPM
91+
let mut manager = TpmManager::new();
8492

85-
/// Benchmark #4: Verify signature
86-
/// ------------------------------
87-
/// This benchmark measures the performance of the [`FapiContext::verify_signature()`] function.
88-
fn bench_verify_signature<M: Measurement>(group: &mut BenchmarkGroup<M>) {
89-
// Initialize TPM
90-
let mut manager = TpmManager::new();
91-
92-
// Create siging key
93-
let sign_key_path = format!("{}/sign_key", &manager.1);
94-
manager.0.create_key(&sign_key_path, Some(&FLAGS_SIGNING), None, None).expect("Failed to create sign key!");
95-
96-
// Sign message
97-
let digest = [0u8; 32usize];
98-
let signature = manager.0.sign(&sign_key_path, None, &digest, false, false).expect("Failed to sign message!");
99-
100-
// Measurement!
101-
group.bench_function("verify_signature", |b| {
102-
b.iter(|| _verify_signature(&mut manager.0, &sign_key_path, black_box(&digest), &black_box(&signature).sign_value))
103-
});
104-
}
93+
// Create siging key
94+
let sign_key_path = format!("{}/sign_key", &manager.1);
95+
manager.0.create_key(&sign_key_path, Some(&FLAGS_SIGNING), None, None).expect("Failed to create sign key!");
96+
97+
// Sign message
98+
let digest = [0u8; 32usize];
99+
let signature = manager.0.sign(&sign_key_path, None, &digest, false, false).expect("Failed to sign message!");
100+
101+
// Measurement!
102+
group.bench_function("verify_signature", |b| {
103+
b.iter(|| _verify_signature(&mut manager.0, &sign_key_path, black_box(&digest), &black_box(&signature).sign_value))
104+
});
105+
}
106+
107+
fn _verify_signature(context: &mut FapiContext, sign_key_path: &str, digest: &[u8], signature: &[u8]) {
108+
let result = black_box(context.verify_signature(sign_key_path, digest, signature).expect("Failed to verify signature!"));
109+
assert!(result);
110+
}
105111

106-
fn _verify_signature(context: &mut FapiContext, sign_key_path: &str, digest: &[u8], signature: &[u8]) {
107-
let result = black_box(context.verify_signature(sign_key_path, digest, signature).expect("Failed to verify signature!"));
108-
assert!(result);
112+
/// FAPI benchmarks runner
113+
/// ----------------------
114+
/// This is the entry point for running the `fapi_rs` benchmarks
115+
pub fn run(c: &mut Criterion) {
116+
let mut group = c.benchmark_group("fapi_rs");
117+
group.sampling_mode(SamplingMode::Flat).warm_up_time(Duration::from_secs(12)).measurement_time(Duration::from_secs(30));
118+
119+
// Run benchmarks
120+
get_random(&mut group);
121+
create_key(&mut group);
122+
sign(&mut group);
123+
verify_signature(&mut group);
124+
125+
// Finish benchmark
126+
group.finish();
127+
}
109128
}
110129

111130
// ==========================================================================
@@ -167,19 +186,5 @@ impl Drop for TpmManager {
167186
// Main
168187
// ==========================================================================
169188

170-
fn bench(c: &mut Criterion) {
171-
let mut group = c.benchmark_group("fapi_rs");
172-
group.sampling_mode(SamplingMode::Flat).warm_up_time(Duration::from_secs(12)).measurement_time(Duration::from_secs(30));
173-
174-
// Run benchmarks
175-
bench_get_random(&mut group);
176-
bench_create_key(&mut group);
177-
bench_sign(&mut group);
178-
bench_verify_signature(&mut group);
179-
180-
// Finish benchmark
181-
group.finish();
182-
}
183-
184-
criterion_group!(benches, bench);
189+
criterion_group!(benches, bench_fapi::run);
185190
criterion_main!(benches);
Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,24 @@
11
{
2-
"curveID": "TPM2_ECC_NIST_P256",
2+
"type": "TPM2_ALG_ECC",
3+
"nameAlg": "TPM2_ALG_SHA256",
4+
"srk_template": "system,restricted,decrypt,0x81000001",
5+
"srk_description": "Storage root key SRK",
6+
"srk_persistent": 0,
7+
"ek_template": "system,restricted,decrypt",
8+
"ek_description": "Endorsement key EK",
39
"ecc_signing_scheme": {
10+
"scheme": "TPM2_ALG_ECDSA",
411
"details": {
512
"hashAlg": "TPM2_ALG_SHA256"
6-
},
7-
"scheme": "TPM2_ALG_ECDSA"
13+
}
814
},
9-
"ek_description": "Endorsement key EK",
10-
"ek_policy": {
11-
"description": "Endorsement hierarchy used for policy secret.",
12-
"policy": [
13-
{
14-
"objectName": "4000000b",
15-
"type": "POLICYSECRET"
16-
}
17-
]
15+
"sym_mode": "TPM2_ALG_CFB",
16+
"sym_parameters": {
17+
"algorithm": "TPM2_ALG_AES",
18+
"keyBits": "128",
19+
"mode": "TPM2_ALG_CFB"
1820
},
19-
"ek_template": "system,restricted,decrypt",
20-
"nameAlg": "TPM2_ALG_SHA256",
21+
"sym_block_size": 16,
2122
"pcr_selection": [
2223
{
2324
"hash": "TPM2_ALG_SHA256",
@@ -33,15 +34,14 @@
3334
]
3435
}
3536
],
36-
"srk_description": "Storage root key SRK",
37-
"srk_persistent": 0,
38-
"srk_template": "system,restricted,decrypt,0x81000001",
39-
"sym_block_size": 16,
40-
"sym_mode": "TPM2_ALG_CFB",
41-
"sym_parameters": {
42-
"algorithm": "TPM2_ALG_AES",
43-
"keyBits": "128",
44-
"mode": "TPM2_ALG_CFB"
45-
},
46-
"type": "TPM2_ALG_ECC"
37+
"curveID": "TPM2_ECC_NIST_P256",
38+
"ek_policy": {
39+
"description": "Endorsement hierarchy used for policy secret.",
40+
"policy": [
41+
{
42+
"type": "POLICYSECRET",
43+
"objectName": "4000000b"
44+
}
45+
]
46+
}
4747
}
File renamed without changes.

tests/14_certificate_test.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ fn test_get_platform_certificates() {
230230

231231
fn generate_certificate(config: &TestConfiguration, public_key: JsonValue, common_name: &str) -> Option<String> {
232232
let common_name = common_name.trim();
233-
assert!(!common_name.is_empty() && common_name.chars().all(|c| char::is_ascii_alphanumeric(&c) || c == '\x20'));
233+
assert!(!common_name.is_empty() && common_name.chars().all(is_valid_name_char));
234234

235235
let key_suffix = get_key_suffix(config).expect("Failed to determine key type!");
236236
let public_key = public_key["pem_ext_public"].as_str()?;
@@ -258,6 +258,10 @@ fn generate_certificate(config: &TestConfiguration, public_key: JsonValue, commo
258258
}
259259
}
260260

261+
fn is_valid_name_char(c: char) -> bool {
262+
char::is_ascii_alphanumeric(&c) || c == '\x20'
263+
}
264+
261265
fn get_key_suffix(config: &TestConfiguration) -> Option<&'static str> {
262266
match get_key_type(config.prof_name()) {
263267
Some(KeyType::RsaKey) => Some("rsa"),

tests/common/setup.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ impl<'a> TestConfiguration<'a> {
108108
if fs::metadata(&conf_file).is_ok_and(|file_info| file_info.is_file()) {
109109
debug!("Re-using the existing FAPI configuration!");
110110
} else {
111-
Self::write_fapi_config(&conf_file, &data_path, &work_path, prof_name, tcti_conf);
111+
Self::write_fapi_config(&conf_file, &data_path.join("fapi-config"), &work_path, prof_name, tcti_conf);
112112
}
113113

114114
unsafe {
@@ -118,7 +118,7 @@ impl<'a> TestConfiguration<'a> {
118118
Self { uniq_lock, prof_name, data_path, work_path, finalizer }
119119
}
120120

121-
fn write_fapi_config(conf_file: &Path, data_path: &Path, work_path: &Path, prof_name: &str, tcti_conf: &str) {
121+
fn write_fapi_config(conf_file: &Path, template_path: &Path, work_path: &Path, prof_name: &str, tcti_conf: &str) {
122122
if Path::try_exists(work_path).unwrap_or(true) {
123123
fs::remove_dir_all(work_path).expect("Failed to remove existing directory!");
124124
}
@@ -145,7 +145,7 @@ impl<'a> TestConfiguration<'a> {
145145
debug!("Logs directory: \"{}\"", logs_path.to_str().unwrap());
146146
fs::create_dir_all(&logs_path).expect("Failed to create subdirectories!");
147147

148-
let mut content = fs::read_to_string(data_path.join("fapi-config.json.template")).expect("Failed to read input file!");
148+
let mut content = fs::read_to_string(template_path.join("fapi-config.json.template")).expect("Failed to read input file!");
149149
content = content.replace("{{TCTI_CFG}}", tcti_conf);
150150
content = content.replace("{{PROF_CFG}}", prof_name);
151151
content = content.replace("{{PROF_DIR}}", prof_path.to_str().unwrap());
@@ -156,7 +156,7 @@ impl<'a> TestConfiguration<'a> {
156156
trace!("FAPI conf data: {}", content.trim());
157157
fs::write(conf_file, &content).expect("Failed to write configuration to output file!");
158158

159-
for entry in fs::read_dir(data_path.join("profiles")).unwrap().flatten() {
159+
for entry in fs::read_dir(template_path.join("profiles")).unwrap().flatten() {
160160
let fname = entry.file_name();
161161
if fname.to_str().is_some_and(|str| str.starts_with("P_")) {
162162
let (path_src, path_dst) = (entry.path(), prof_path.join(fname));
File renamed without changes.

tests/data/fapi-config/profiles

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
../../../examples/data/profiles

0 commit comments

Comments
 (0)