interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-security / src / tpm.rs

237 lines · 8935 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Hardware TPM 2.0 secret provider implementation for AIEN.
17
18use crate::secret::{
19 SealedSecret, SecretCapabilities, SecretError, SecretProtectionLevel, SecretProvider,
20};
21use std::collections::HashMap;
22use std::io::Write;
23use std::path::{Path, PathBuf};
24use std::process::{Command, Stdio};
25use zeroize::Zeroizing;
26
27/// Hardware TPM 2.0 provider backed by platform sealed storage.
28pub struct Tpm2SecretProvider {
29 vault_binary: PathBuf,
30 tpm_device: PathBuf,
31}
32
33impl Tpm2SecretProvider {
34 /// Probe system for hardware TPM availability.
35 pub fn probe() -> Self {
36 let default_device = PathBuf::from("/dev/tpmrm0");
37 let default_vault = if let Ok(home) = std::env::var("HOME") {
38 let candidate = Path::new(&home).join(".local/bin/atlas-vault");
39 if candidate.exists() {
40 candidate
41 } else {
42 PathBuf::from("atlas-vault")
43 }
44 } else {
45 PathBuf::from("atlas-vault")
46 };
47
48 Self {
49 vault_binary: default_vault,
50 tpm_device: default_device,
51 }
52 }
53
54 /// Provider for an explicit vault binary and TPM device node.
55 pub fn with_paths(vault_binary: impl Into<PathBuf>, tpm_device: impl Into<PathBuf>) -> Self {
56 Self {
57 vault_binary: vault_binary.into(),
58 tpm_device: tpm_device.into(),
59 }
60 }
61
62 /// Check if the hardware TPM device node exists on this system.
63 pub fn is_hardware_present(&self) -> bool {
64 self.tpm_device.exists()
65 }
66}
67
68impl Default for Tpm2SecretProvider {
69 fn default() -> Self {
70 Self::probe()
71 }
72}
73
74impl SecretProvider for Tpm2SecretProvider {
75 fn capabilities(&self) -> SecretCapabilities {
76 SecretCapabilities {
77 protection_level: SecretProtectionLevel::HardwareBackedSealed,
78 can_seal: true,
79 can_unseal: true,
80 hardware_bound: true,
81 persistent_at_rest: true,
82 }
83 }
84
85 fn protection_level(&self) -> SecretProtectionLevel {
86 SecretProtectionLevel::HardwareBackedSealed
87 }
88
89 fn seal(&self, name: &str, secret: &[u8]) -> Result<SealedSecret, SecretError> {
90 let secret_str = std::str::from_utf8(secret).map_err(|_| {
91 SecretError::CryptoError("TPM vault requires UTF-8 compatible secret input".to_string())
92 })?;
93
94 // `atlas-vault add <NAME>` reads the value from standard input. The value never goes on
95 // the command line, where other local processes could read it.
96 let mut child = Command::new(&self.vault_binary)
97 .args(["add", name])
98 .stdin(Stdio::piped())
99 .stdout(Stdio::piped())
100 .stderr(Stdio::piped())
101 .spawn()
102 .map_err(|e| SecretError::IoError(format!("Failed to execute vault command: {}", e)))?;
103 // Dropping `stdin` closes it, so the vault sees end of input. The child is always waited
104 // for, even when the write fails, and its own error is reported first.
105 let written = match child.stdin.take() {
106 Some(mut stdin) => stdin.write_all(secret_str.as_bytes()),
107 None => Err(std::io::Error::other("vault command stdin is not piped")),
108 };
109 let output = child
110 .wait_with_output()
111 .map_err(|e| SecretError::IoError(format!("Failed to execute vault command: {}", e)))?;
112
113 if !output.status.success() {
114 let err_msg = String::from_utf8_lossy(&output.stderr);
115 return Err(SecretError::CryptoError(format!(
116 "TPM vault add failed: {}",
117 err_msg.trim()
118 )));
119 }
120 written.map_err(|e| {
121 SecretError::IoError(format!("Failed to write secret to vault command: {}", e))
122 })?;
123
124 Ok(SealedSecret {
125 name: name.to_string(),
126 ciphertext: Vec::new(),
127 protection_level: SecretProtectionLevel::HardwareBackedSealed,
128 metadata: HashMap::new(),
129 })
130 }
131
132 fn unseal(&self, secret: &SealedSecret) -> Result<Zeroizing<Vec<u8>>, SecretError> {
133 self.resolve(&secret.name)
134 }
135
136 fn delete(&self, name: &str) -> Result<(), SecretError> {
137 let output = Command::new(&self.vault_binary)
138 .args(["remove", name])
139 .output()
140 .map_err(|e| SecretError::IoError(format!("Failed to execute vault command: {}", e)))?;
141
142 if !output.status.success() {
143 let err_msg = String::from_utf8_lossy(&output.stderr);
144 return Err(SecretError::CryptoError(format!(
145 "TPM vault remove failed: {}",
146 err_msg.trim()
147 )));
148 }
149
150 Ok(())
151 }
152
153 fn resolve(&self, name: &str) -> Result<Zeroizing<Vec<u8>>, SecretError> {
154 let output = Command::new(&self.vault_binary)
155 .args(["get", name])
156 .output()
157 .map_err(|e| SecretError::IoError(format!("Failed to execute vault command: {}", e)))?;
158
159 if !output.status.success() {
160 return Err(SecretError::NotFound(name.to_string()));
161 }
162
163 let val = String::from_utf8_lossy(&output.stdout).trim().to_string();
164 if val.is_empty() {
165 return Err(SecretError::NotFound(name.to_string()));
166 }
167
168 Ok(Zeroizing::new(val.into_bytes()))
169 }
170}
171
172#[cfg(all(test, unix))]
173mod tests {
174 use super::*;
175 use std::os::unix::fs::PermissionsExt;
176
177 /// A stand-in for `atlas-vault` that records its arguments and standard input and keeps one
178 /// value in a file, so the adapter can be checked without a TPM.
179 fn stub_vault(dir: &Path) -> PathBuf {
180 let script = dir.join("vault-stub");
181 let body = format!(
182 "#!/bin/sh\nd='{d}'\nprintf '%s\\n' \"$*\" >> \"$d/argv\"\ncase \"$1\" in\n add) cat > \"$d/stdin\"; cp \"$d/stdin\" \"$d/value\" ;;\n get) [ -f \"$d/value\" ] || exit 1; cat \"$d/value\" ;;\n remove) [ -f \"$d/value\" ] || exit 1; rm \"$d/value\" ;;\n *) echo \"unknown command $1\" >&2; exit 2 ;;\nesac\n",
183 d = dir.display()
184 );
185 std::fs::write(&script, body).unwrap();
186 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap();
187 script
188 }
189
190 fn scratch_dir(tag: &str) -> PathBuf {
191 let dir = std::env::temp_dir().join(format!(
192 "aien-security-vault-{}-{}",
193 tag,
194 std::process::id()
195 ));
196 let _ = std::fs::remove_dir_all(&dir);
197 std::fs::create_dir_all(&dir).unwrap();
198 dir
199 }
200
201 #[test]
202 fn seal_uses_stdin_not_argv_remove_round_trips_and_refusal_is_an_error() {
203 let dir = scratch_dir("roundtrip");
204 let provider = Tpm2SecretProvider::with_paths(stub_vault(&dir), dir.join("no-tpm"));
205 let value = b"test-value-7f3a";
206
207 provider.seal("AIEN_TEST_NAME", value).expect("seal");
208 assert_eq!(std::fs::read(dir.join("stdin")).unwrap(), value);
209 assert_eq!(
210 &*provider.resolve("AIEN_TEST_NAME").expect("resolve"),
211 value
212 );
213 provider.delete("AIEN_TEST_NAME").expect("remove");
214 assert!(provider.resolve("AIEN_TEST_NAME").is_err());
215
216 let argv = std::fs::read_to_string(dir.join("argv")).unwrap();
217 assert_eq!(
218 argv,
219 "add AIEN_TEST_NAME\nget AIEN_TEST_NAME\nremove AIEN_TEST_NAME\nget AIEN_TEST_NAME\n"
220 );
221 assert!(!argv.contains("test-value-7f3a"));
222
223 // A vault that refuses the add is reported as an error. One test writes both scripts, so
224 // no other test in this module forks while a script file is open for writing.
225 let script = dir.join("vault-fail");
226 std::fs::write(
227 &script,
228 "#!/bin/sh\ncat > /dev/null\necho refused >&2\nexit 1\n",
229 )
230 .unwrap();
231 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap();
232 let provider = Tpm2SecretProvider::with_paths(script, dir.join("no-tpm"));
233 let err = provider.seal("AIEN_TEST_NAME", b"v").unwrap_err();
234 assert!(matches!(err, SecretError::CryptoError(ref m) if m.contains("refused")));
235 let _ = std::fs::remove_dir_all(&dir);
236 }
237}