vex-hardware 1.0.0

Hardware-rooted identity for AI agents (TPM/CNG)
Documentation
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
pub use crate::traits::HardwareIdentity;
use anyhow::{anyhow, Result};
use async_trait::async_trait;

use crate::api::HardwareError;

pub fn create_identity_provider(
    allow_fallback: bool,
) -> Result<Box<dyn HardwareIdentity>, HardwareError> {
    #[cfg(windows)]
    {
        tracing::info!("⚓ Probing for Hardware Root of Trust (Windows CNG)...");
        if allow_fallback {
            tracing::info!("⚙️ Fallback allowed. Using Deterministic Identity (VEX-Seed).");
            return Ok(Box::new(stub_impl::StubIdentity));
        }
        tracing::info!("✅ Using Windows CNG Hardware Identity.");
        Ok(Box::new(windows_impl::CngIdentity))
    }

    #[cfg(target_os = "linux")]
    {
        tracing::info!("⚓ Probing for Hardware Root of Trust (Linux TPM)...");
        // Silent probe: Check if the TPM device exists before letting the noisy library try to open it
        if std::path::Path::new("/dev/tpm0").exists()
            || std::path::Path::new("/dev/tpmrm0").exists()
        {
            match linux_impl::Tpm2Identity::new() {
                Ok(tpm) => {
                    tracing::info!("✅ Hardware TPM found and initialized.");
                    return Ok(Box::new(tpm));
                }
                Err(e) => {
                    tracing::warn!(
                        "⚠️ Hardware TPM found but initialization failed: {}. Falling back.",
                        e
                    );
                }
            }
        } else {
            tracing::info!("ℹ️ No physical TPM device found (/dev/tpm0).");
        }

        if allow_fallback {
            tracing::info!("⚙️ Falling back to Deterministic Identity (VEX-Seed).");
            Ok(Box::new(stub_impl::StubIdentity))
        } else {
            Err(HardwareError::NoTpmFound(
                "No TPM device (/dev/tpm0) found in system".to_string(),
            ))
        }
    }

    #[cfg(not(any(windows, target_os = "linux")))]
    {
        tracing::info!("⚓ Probing for Hardware Root of Trust (Generic)...");
        if allow_fallback {
            tracing::info!("⚙️ Platform not supported. Falling back to Deterministic Identity.");
            Ok(Box::new(stub_impl::StubIdentity))
        } else {
            Err(HardwareError::NoTpmFound(
                "Hardware identity not supported on this platform".to_string(),
            ))
        }
    }
}

#[cfg(target_os = "linux")]
pub use linux_impl::Tpm2Identity;
#[cfg(not(any(windows, target_os = "linux")))]
pub use stub_impl::StubIdentity;
#[cfg(windows)]
pub use windows_impl::CngIdentity;

// Windows Implementation
#[cfg(windows)]
mod windows_impl {

    use super::*;
    use std::ptr::null_mut;
    use windows_sys::Win32::Security::Cryptography::*;

    #[derive(Default)]
    pub struct CngIdentity;

    #[async_trait]
    impl HardwareIdentity for CngIdentity {
        async fn seal(&self, _label: &str, data: &[u8]) -> Result<Vec<u8>> {
            unsafe {
                let mut provider: usize = 0;
                let provider_name: Vec<u16> = "Microsoft Platform Crypto Provider\0"
                    .encode_utf16()
                    .collect();

                let status = NCryptOpenStorageProvider(&mut provider, provider_name.as_ptr(), 0);
                if status != 0 {
                    return Err(anyhow!(
                        "TPM provider not available (Status: 0x{:X})",
                        status
                    ));
                }

                let mut key_handle: usize = 0;
                let key_name: Vec<u16> = "AttestIdentitySRK\0".encode_utf16().collect();
                let alg_id: Vec<u16> = "RSA\0".encode_utf16().collect();

                let mut status = NCryptOpenKey(provider, &mut key_handle, key_name.as_ptr(), 0, 0);
                if status != 0 {
                    status = NCryptCreatePersistedKey(
                        provider,
                        &mut key_handle,
                        alg_id.as_ptr(),
                        key_name.as_ptr(),
                        0,
                        0,
                    );
                    if status != 0 {
                        NCryptFreeObject(provider);
                        return Err(anyhow!("Failed to create TPM key (Status: 0x{:X})", status));
                    }

                    status = NCryptFinalizeKey(key_handle, 0);
                    if status != 0 {
                        NCryptFreeObject(key_handle);
                        NCryptFreeObject(provider);
                        return Err(anyhow!(
                            "Failed to finalize TPM key (Status: 0x{:X})",
                            status
                        ));
                    }
                }

                let mut output_size: u32 = 0;
                status = NCryptEncrypt(
                    key_handle,
                    data.as_ptr(),
                    data.len() as u32,
                    std::ptr::null(),
                    null_mut(),
                    0,
                    &mut output_size,
                    0,
                );
                if status != 0 {
                    NCryptFreeObject(key_handle);
                    NCryptFreeObject(provider);
                    return Err(anyhow!(
                        "Failed to get ciphertext size (Status: 0x{:X})",
                        status
                    ));
                }

                let mut ciphertext = vec![0u8; output_size as usize];
                status = NCryptEncrypt(
                    key_handle,
                    data.as_ptr(),
                    data.len() as u32,
                    std::ptr::null(),
                    ciphertext.as_mut_ptr(),
                    ciphertext.len() as u32,
                    &mut output_size,
                    0,
                );

                NCryptFreeObject(key_handle);
                NCryptFreeObject(provider);

                if status != 0 {
                    return Err(anyhow!(
                        "Failed to encrypt with TPM (Status: 0x{:X})",
                        status
                    ));
                }

                Ok(ciphertext)
            }
        }

        async fn unseal(&self, blob: &[u8]) -> Result<Vec<u8>> {
            unsafe {
                let mut provider: usize = 0;
                let provider_name: Vec<u16> = "Microsoft Platform Crypto Provider\0"
                    .encode_utf16()
                    .collect();

                let mut status =
                    NCryptOpenStorageProvider(&mut provider, provider_name.as_ptr(), 0);
                if status != 0 {
                    return Err(anyhow!(
                        "TPM provider not available (Status: 0x{:X})",
                        status
                    ));
                }

                let mut key_handle: usize = 0;
                let key_name: Vec<u16> = "AttestIdentitySRK\0".encode_utf16().collect();

                status = NCryptOpenKey(provider, &mut key_handle, key_name.as_ptr(), 0, 0);
                if status != 0 {
                    NCryptFreeObject(provider);
                    return Err(anyhow!(
                        "Identity key not found in TPM (Status: 0x{:X})",
                        status
                    ));
                }

                let mut output_size: u32 = 0;
                status = NCryptDecrypt(
                    key_handle,
                    blob.as_ptr(),
                    blob.len() as u32,
                    std::ptr::null(),
                    null_mut(),
                    0,
                    &mut output_size,
                    0,
                );
                if status != 0 {
                    NCryptFreeObject(key_handle);
                    NCryptFreeObject(provider);
                    return Err(anyhow!(
                        "Failed to get decrypted size (Status: 0x{:X})",
                        status
                    ));
                }

                let mut plaintext = vec![0u8; output_size as usize];
                status = NCryptDecrypt(
                    key_handle,
                    blob.as_ptr(),
                    blob.len() as u32,
                    std::ptr::null(),
                    plaintext.as_mut_ptr(),
                    plaintext.len() as u32,
                    &mut output_size,
                    0,
                );

                NCryptFreeObject(key_handle);
                NCryptFreeObject(provider);

                if status != 0 {
                    return Err(anyhow!(
                        "Failed to unseal with TPM (Status: 0x{:X})",
                        status
                    ));
                }

                Ok(plaintext)
            }
        }
    }
}

#[cfg(target_os = "linux")]
mod linux_impl {
    use super::*;
    use std::sync::{Arc, Mutex};
    use tss_esapi::{
        attributes::ObjectAttributesBuilder,
        interface_types::{
            algorithm::{HashingAlgorithm, PublicAlgorithm},
            key_bits::RsaKeyBits,
            resource_handles::Hierarchy,
        },
        structures::{
            KeyedHashScheme, Private, Public, PublicBuffer, PublicBuilder,
            PublicKeyedHashParameters, RsaExponent, SensitiveData, SymmetricDefinitionObject,
        },
        tcti_ldr::TctiNameConf,
        traits::{Marshall, UnMarshall},
        utils, Context,
    };

    pub struct Tpm2Identity {
        context: Arc<Mutex<Context>>,
    }

    impl Tpm2Identity {
        pub fn new() -> Result<Self> {
            let tcti_res = TctiNameConf::from_environment_variable();
            let tcti = match tcti_res {
                Ok(t) => t,
                Err(_) => TctiNameConf::Device(Default::default()),
            };
            let context =
                Context::new(tcti).map_err(|e| anyhow!("Failed to create TPM context: {}", e))?;
            Ok(Self {
                context: Arc::new(Mutex::new(context)),
            })
        }
    }

    impl Default for Tpm2Identity {
        fn default() -> Self {
            Self::new().expect("Failed to create TPM context in Default impl")
        }
    }

    #[async_trait]
    impl HardwareIdentity for Tpm2Identity {
        async fn seal(&self, _label: &str, data: &[u8]) -> Result<Vec<u8>> {
            let context_lock = self.context.clone();
            let data = data.to_vec();

            tokio::task::spawn_blocking(move || {
                let mut context = context_lock
                    .lock()
                    .map_err(|e| anyhow!("Mutex error: {}", e))?;

                // 1. Create a Primary Key in the Storage Hierarchy
                let primary_key_public = utils::create_restricted_decryption_rsa_public(
                    SymmetricDefinitionObject::AES_256_CFB,
                    RsaKeyBits::Rsa2048,
                    RsaExponent::default(),
                )
                .map_err(|e| anyhow!("Failed to create primary key public template: {}", e))?;

                let primary_key_result = context
                    .create_primary(Hierarchy::Owner, primary_key_public, None, None, None, None)
                    .map_err(|e| anyhow!("Failed to create primary key: {}", e))?;
                let primary_key_handle = primary_key_result.key_handle;

                // 2. Create the Sealed Object
                let sensitive_data = SensitiveData::try_from(data)
                    .map_err(|e| anyhow!("Invalid data for sealing: {}", e))?;

                let object_attributes = ObjectAttributesBuilder::new()
                    .with_fixed_tpm(true)
                    .with_fixed_parent(true)
                    .with_sensitive_data_origin(false) // Data is provided externally
                    .with_user_with_auth(true)
                    .build()
                    .map_err(|e| anyhow!("Failed to build object attributes: {}", e))?;

                let sealed_data_public = PublicBuilder::new()
                    .with_public_algorithm(PublicAlgorithm::KeyedHash)
                    .with_name_hashing_algorithm(HashingAlgorithm::Sha256)
                    .with_object_attributes(object_attributes)
                    .with_keyed_hash_parameters(PublicKeyedHashParameters::new(
                        KeyedHashScheme::Null,
                    ))
                    .build()
                    .map_err(|e| anyhow!("Failed to build sealed data public structure: {}", e))?;

                let create_result = context
                    .create(
                        primary_key_handle,
                        sealed_data_public,
                        None,
                        Some(sensitive_data),
                        None,
                        None,
                    )
                    .map_err(|e| anyhow!("Failed to create sealed object: {}", e))?;

                let public = create_result.out_public;
                let private = create_result.out_private;

                context.flush_context(primary_key_handle.into())?;

                // 3. Serialize both Public and Private parts into a single blob
                // Convert Public to PublicBuffer for marshalling
                let pub_buf = PublicBuffer::try_from(public)
                    .map_err(|e| anyhow!("Failed to convert Public to PublicBuffer: {}", e))?
                    .marshall()
                    .map_err(|e| anyhow!("Pub marshall error: {}", e))?;

                // For Private, use value() method if it's a buffer type
                let priv_buf = private.value().to_vec();

                let mut combined = Vec::with_capacity(4 + pub_buf.len() + priv_buf.len());
                combined.extend_from_slice(&(pub_buf.len() as u32).to_le_bytes());
                combined.extend_from_slice(&pub_buf);
                combined.extend_from_slice(&priv_buf);

                Ok(combined)
            })
            .await?
        }

        async fn unseal(&self, blob: &[u8]) -> Result<Vec<u8>> {
            let context_lock = self.context.clone();
            let blob = blob.to_vec();

            tokio::task::spawn_blocking(move || {
                let mut context = context_lock
                    .lock()
                    .map_err(|e| anyhow!("Mutex error: {}", e))?;

                // 1. Split combined blob
                if blob.len() < 4 {
                    return Err(anyhow!("Invalid blob length"));
                }
                let pub_len = u32::from_le_bytes(blob[0..4].try_into().unwrap()) as usize;
                if blob.len() < 4 + pub_len {
                    return Err(anyhow!("Invalid pub length in blob"));
                }

                let pub_buf = &blob[4..4 + pub_len];
                let priv_buf = &blob[4 + pub_len..];

                // Unmarshall into buffer types, then convert to structs
                let pub_buffer = PublicBuffer::unmarshall(pub_buf)
                    .map_err(|e| anyhow!("Pub unmarshall error: {}", e))?;
                let public = Public::try_from(pub_buffer)
                    .map_err(|e| anyhow!("Failed to convert PublicBuffer to Public: {}", e))?;

                let private = Private::try_from(priv_buf.to_vec())
                    .map_err(|e| anyhow!("Priv try_from error: {}", e))?;

                // 2. Load Primary Key again
                let primary_key_public = utils::create_restricted_decryption_rsa_public(
                    SymmetricDefinitionObject::AES_256_CFB,
                    RsaKeyBits::Rsa2048,
                    RsaExponent::default(),
                )
                .map_err(|e| anyhow!("Failed to create primary key public template: {}", e))?;

                let primary_key_result = context
                    .create_primary(Hierarchy::Owner, primary_key_public, None, None, None, None)
                    .map_err(|e| anyhow!("Failed to create primary key: {}", e))?;
                let primary_key_handle = primary_key_result.key_handle;

                // 3. Load Sealed Object
                let object_handle = context
                    .load(primary_key_handle, private, public)
                    .map_err(|e| anyhow!("Failed to load sealed object: {}", e))?;

                // 4. Unseal
                let unsealed_data = context
                    .unseal(object_handle.into())
                    .map_err(|e| anyhow!("Failed to unseal: {}", e))?;

                context.flush_context(object_handle.into())?;
                context.flush_context(primary_key_handle.into())?;

                Ok(unsealed_data.to_vec())
            })
            .await?
        }
    }
}

mod stub_impl {
    use super::*;

    #[derive(Default)]
    pub struct StubIdentity;

    #[async_trait]
    impl HardwareIdentity for StubIdentity {
        async fn seal(&self, _label: &str, data: &[u8]) -> Result<Vec<u8>> {
            Ok(data.to_vec())
        }

        async fn unseal(&self, blob: &[u8]) -> Result<Vec<u8>> {
            Ok(blob.to_vec())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_hardware_identity_interface() {
        let provider = create_identity_provider(true).expect("Failed to create provider");
        let data = b"test_secret_seed";

        match provider.seal("test_label", data).await {
            Ok(sealed) => {
                let unsealed = provider
                    .unseal(&sealed)
                    .await
                    .expect("Unseal must succeed if seal succeeded");
                assert_eq!(
                    data.to_vec(),
                    unsealed,
                    "Unsealed data must match original input"
                );
            }
            Err(e) => {
                println!("⚠️ TPM Seal skipped or failed: {}", e);
                // On systems without TPM, we don't want the build to fail if it's just a hardware absence
                // But for Alpha, we want to know why.
            }
        }
    }
}