main.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. use btlib::{
  2. blocktree::{Blocktree, ModeAuthorizer},
  3. crypto::{
  4. tpm::{TpmCredStore, TpmCreds},
  5. CredStore,
  6. },
  7. };
  8. use fuse_backend_rs::{
  9. api::server::Server,
  10. transport::{Error, FuseSession},
  11. };
  12. use log::error;
  13. use std::{
  14. ffi::{c_char, CString},
  15. fs::{self, File},
  16. io,
  17. os::fd::FromRawFd,
  18. os::{raw::c_int, unix::ffi::OsStrExt},
  19. path::{Path, PathBuf},
  20. str::FromStr,
  21. sync::mpsc::Sender,
  22. };
  23. use tss_esapi::{
  24. tcti_ldr::{TabrmdConfig, TctiNameConf},
  25. Context,
  26. };
  27. const DEFAULT_TABRMD: &str = "bus_type=session";
  28. const MOUNT_OPTIONS: &str = "default_permissions";
  29. const FSNAME: &str = "btfuse";
  30. const FSTYPE: &str = "bt";
  31. trait PathExt {
  32. fn try_create_dir(&self) -> io::Result<()>;
  33. }
  34. impl<T: AsRef<Path>> PathExt for T {
  35. fn try_create_dir(&self) -> io::Result<()> {
  36. match fs::create_dir(self) {
  37. Ok(_) => Ok(()),
  38. Err(err) => match err.kind() {
  39. io::ErrorKind::AlreadyExists => Ok(()),
  40. _ => Err(err),
  41. },
  42. }
  43. }
  44. }
  45. #[link(name = "fuse3")]
  46. extern "C" {
  47. /// Opens a channel to the kernel.
  48. fn fuse_open_channel(mountpoint: *const c_char, options: *const c_char) -> c_int;
  49. }
  50. /// Calls into libfuse3 to mount this file system at the given path. The file descriptor to use
  51. /// to communicate with the kernel is returned.
  52. fn mount_at<P: AsRef<Path>>(mnt_point: P) -> File {
  53. let mountpoint = CString::new(mnt_point.as_ref().as_os_str().as_bytes()).unwrap();
  54. let options = CString::new(MOUNT_OPTIONS).unwrap();
  55. let raw_fd = unsafe { fuse_open_channel(mountpoint.as_ptr(), options.as_ptr()) };
  56. unsafe { File::from_raw_fd(raw_fd) }
  57. }
  58. /// A fuse daemon process.
  59. struct FuseDaemon<'a> {
  60. /// The path of the directory to store all file system information in.
  61. path: &'a Path,
  62. /// The configuration string to use to connect to a Tabrmd instance.
  63. tabrmd_config: &'a str,
  64. /// An optional [Sender] which is called when this daemon has finished starting up.
  65. started_signal: Option<Sender<()>>,
  66. }
  67. impl<'a> FuseDaemon<'a> {
  68. fn new(path: &'a Path, tabrmd_config: &'a str) -> FuseDaemon<'_> {
  69. FuseDaemon {
  70. path,
  71. tabrmd_config,
  72. started_signal: None,
  73. }
  74. }
  75. fn tpm_state_path<P: AsRef<Path>>(path: P) -> PathBuf {
  76. path.as_ref().join("tpm_state")
  77. }
  78. fn mnt_path<P: AsRef<Path>>(path: P) -> PathBuf {
  79. path.as_ref().join("mnt")
  80. }
  81. fn server<P: AsRef<Path>>(&self, mnt_path: P) -> Server<Blocktree<TpmCreds, ModeAuthorizer>> {
  82. let empty = fs::read_dir(&mnt_path)
  83. .expect("failed to read mountdir")
  84. .next()
  85. .is_none();
  86. let context = Context::new(TctiNameConf::Tabrmd(
  87. TabrmdConfig::from_str(self.tabrmd_config).expect("failed to parse Tabrmd config"),
  88. ))
  89. .expect("failed to connect to Tabrmd");
  90. let cred_store = TpmCredStore::new(context, Self::tpm_state_path(self.path))
  91. .expect("failed to create TpmCredStore");
  92. let node_creds = cred_store
  93. .node_creds()
  94. .expect("failed to retrieve node creds");
  95. let bt_path = self.path.join("bt");
  96. bt_path
  97. .try_create_dir()
  98. .expect("failed to create blocktree directory");
  99. let fs = if empty {
  100. Blocktree::new_empty(bt_path, 0, node_creds, ModeAuthorizer {})
  101. } else {
  102. Blocktree::new_existing(bt_path, node_creds, ModeAuthorizer {})
  103. }
  104. .expect("failed to create blocktree");
  105. Server::new(fs)
  106. }
  107. fn fuse_session<P: AsRef<Path>>(&self, mnt_path: P) -> FuseSession {
  108. self.path
  109. .try_create_dir()
  110. .expect("failed to create main directory");
  111. let mut session = FuseSession::new(mnt_path.as_ref(), FSNAME, FSTYPE, false)
  112. .expect("failed to create FUSE session");
  113. session.set_fuse_file(mount_at(mnt_path));
  114. session
  115. }
  116. fn start(&self) {
  117. let mnt_path = Self::mnt_path(self.path);
  118. mnt_path
  119. .try_create_dir()
  120. .expect("failed to create mount directory");
  121. let server = self.server(&mnt_path);
  122. let session = self.fuse_session(&mnt_path);
  123. drop(mnt_path);
  124. let mut channel = session
  125. .new_channel()
  126. .expect("failed to create FUSE channel");
  127. if let Some(tx) = self.started_signal.as_ref() {
  128. tx.send(()).expect("failed to send started signal");
  129. }
  130. loop {
  131. match channel.get_request() {
  132. Ok(Some((reader, writer))) => {
  133. if let Err(err) = server.handle_message(reader, writer.into(), None, None) {
  134. error!("error while handling FUSE message: {err}");
  135. }
  136. }
  137. Ok(None) => break,
  138. Err(err) => {
  139. match err {
  140. // Occurs when the file system is unmounted.
  141. Error::SessionFailure(_) => break,
  142. _ => error!("{err}"),
  143. }
  144. }
  145. }
  146. }
  147. }
  148. }
  149. fn main() {
  150. env_logger::init();
  151. let main_dir = std::env::args().nth(1).expect("no mount point given");
  152. let main_dir =
  153. PathBuf::from_str(main_dir.as_str()).expect("failed to convert mount point to PathBuf");
  154. let tabrmd_string = std::env::var("BT_TABRMD").ok();
  155. let tabrmd_str = tabrmd_string
  156. .as_ref()
  157. .map_or(DEFAULT_TABRMD, |s| s.as_str());
  158. let daemon = FuseDaemon::new(&main_dir, tabrmd_str);
  159. daemon.start();
  160. }
  161. #[cfg(test)]
  162. mod test {
  163. use std::{
  164. ffi::{OsStr, OsString},
  165. fs::{
  166. create_dir, hard_link, metadata, read, read_dir, remove_dir, remove_file, rename,
  167. set_permissions, write, Permissions, ReadDir,
  168. },
  169. os::unix::fs::PermissionsExt,
  170. sync::mpsc::{channel, Receiver},
  171. thread::JoinHandle,
  172. time::Duration,
  173. };
  174. use btlib::{crypto::Creds, log::BuilderExt, Epoch, Principaled};
  175. use swtpm_harness::SwtpmHarness;
  176. use tempdir::TempDir;
  177. use super::*;
  178. /// Unmounts the file system at the given path.
  179. fn unmount<P: AsRef<Path>>(mnt_path: P) {
  180. const PROG: &str = "fusermount";
  181. let mnt_path = mnt_path
  182. .as_ref()
  183. .as_os_str()
  184. .to_str()
  185. .expect("failed to convert mnt_path to `str`");
  186. let code = std::process::Command::new(PROG)
  187. .args(["-u", mnt_path])
  188. .status()
  189. .expect("waiting for exit status failed")
  190. .code()
  191. .expect("code returned None");
  192. if code != 0 {
  193. panic!("{PROG} exited with a non-zero status: {code}");
  194. }
  195. }
  196. fn file_names(read_dir: ReadDir) -> impl Iterator<Item = OsString> {
  197. read_dir.map(|entry| entry.unwrap().file_name())
  198. }
  199. struct TestCase {
  200. temp_path_rx: Receiver<PathBuf>,
  201. mnt_path: Option<PathBuf>,
  202. handle: Option<JoinHandle<()>>,
  203. }
  204. impl TestCase {
  205. const ROOT_PASSWD: &str = "Gnurlingwheel";
  206. fn new() -> TestCase {
  207. let (tx, rx) = channel();
  208. let (started_tx, started_rx) = channel();
  209. let handle = std::thread::spawn(move || {
  210. let dir = TempDir::new("btfuse").expect("failed to create TempDir");
  211. tx.send(dir.path().to_owned()).expect("send failed");
  212. let swtpm = SwtpmHarness::new().expect("failed to start swtpm");
  213. {
  214. let context = swtpm.context().expect("failed to create TPM context");
  215. let cred_store =
  216. TpmCredStore::new(context, FuseDaemon::tpm_state_path(dir.path()))
  217. .expect("failed to create TpmCredStore");
  218. let root_creds = cred_store
  219. .gen_root_creds(Self::ROOT_PASSWD)
  220. .expect("failed to gen root creds");
  221. let mut node_creds = cred_store.node_creds().expect("failed to get node creds");
  222. let expires = Epoch::now() + Duration::from_secs(3600);
  223. let writecap = root_creds
  224. .issue_writecap(node_creds.principal(), vec![], expires)
  225. .expect("failed to issue writecap to node creds");
  226. cred_store
  227. .assign_node_writecap(&mut node_creds, writecap)
  228. .expect("failed to assign writecap");
  229. }
  230. let mut daemon = FuseDaemon::new(dir.path(), swtpm.tabrmd_config());
  231. daemon.started_signal = Some(started_tx);
  232. daemon.start()
  233. });
  234. started_rx
  235. .recv_timeout(Duration::from_secs(1))
  236. .expect("failed to receive started signal from `FuseDaemon`");
  237. TestCase {
  238. temp_path_rx: rx,
  239. mnt_path: None,
  240. handle: Some(handle),
  241. }
  242. }
  243. fn mnt_path(&mut self) -> &PathBuf {
  244. self.mnt_path.get_or_insert_with(|| {
  245. let temp_path = self
  246. .temp_path_rx
  247. .recv_timeout(Duration::from_secs(1))
  248. .expect("receive failed");
  249. FuseDaemon::mnt_path(temp_path)
  250. })
  251. }
  252. fn wait(&mut self) {
  253. if let Some(handle) = self.handle.take() {
  254. handle.join().expect("join failed");
  255. }
  256. }
  257. fn unmount_and_wait(&mut self) {
  258. // If `handle` has already been taken that means `wait` has already been called. If
  259. // this thread called `wait` and subsequently became unblocked, we know that the FUSE
  260. // thread halted, which only happens when the file system is unmounted. Hence
  261. // we don't have to unmount it, nor wait for the FUSE thread.
  262. if self.handle.is_none() {
  263. return;
  264. }
  265. let mnt_path = self.mnt_path();
  266. unmount(mnt_path);
  267. self.wait();
  268. }
  269. }
  270. impl Drop for TestCase {
  271. fn drop(&mut self) {
  272. self.unmount_and_wait();
  273. }
  274. }
  275. /// Creates a new file system and mounts it at `/tmp/btfuse.<random>/mnt` so it can be
  276. /// tested manually.
  277. //#[test]
  278. #[allow(dead_code)]
  279. fn manual_test() {
  280. std::env::set_var("RUST_LOG", "debug");
  281. env_logger::Builder::from_default_env().btformat().init();
  282. let mut case = TestCase::new();
  283. case.wait();
  284. }
  285. /// Tests if the file system can be mount then unmounted successfully.
  286. #[test]
  287. fn mount_then_unmount() {
  288. let _ = TestCase::new();
  289. }
  290. #[test]
  291. fn write_read() {
  292. const EXPECTED: &[u8] =
  293. b"The paths to failure are uncountable, yet to success there is but one.";
  294. let mut case = TestCase::new();
  295. let file_path = case.mnt_path().join("file");
  296. write(&file_path, EXPECTED).expect("write failed");
  297. let actual = read(&file_path).expect("read failed");
  298. assert_eq!(EXPECTED, actual);
  299. }
  300. #[test]
  301. fn create_file_then_readdir() {
  302. const DATA: &[u8] = b"Au revoir Shoshanna!";
  303. let file_name = OsStr::new("landa_dialog.txt");
  304. let expected = [file_name];
  305. let mut case = TestCase::new();
  306. let mnt_path = case.mnt_path();
  307. let file_path = mnt_path.join(file_name);
  308. write(&file_path, DATA).expect("write failed");
  309. let first = file_names(read_dir(&mnt_path).expect("read_dir failed"));
  310. assert!(first.eq(expected));
  311. let second = file_names(read_dir(&mnt_path).expect("read_dir failed"));
  312. assert!(second.eq(expected));
  313. }
  314. #[test]
  315. fn create_then_delete_file() {
  316. const DATA: &[u8] = b"The universe is hostile, so impersonal. Devour to survive";
  317. let file_name = OsStr::new("tool_lyrics.txt");
  318. let mut case = TestCase::new();
  319. let mnt_path = case.mnt_path();
  320. let file_path = mnt_path.join(file_name);
  321. write(&file_path, DATA).expect("write failed");
  322. remove_file(&file_path).expect("remove_file failed");
  323. let expected: [&OsStr; 0] = [];
  324. assert!(file_names(read_dir(&mnt_path).expect("read_dir failed")).eq(expected))
  325. }
  326. #[test]
  327. fn hard_link_then_remove() {
  328. const EXPECTED: &[u8] = b"And the lives we've reclaimed";
  329. let name1 = OsStr::new("refugee_lyrics.txt");
  330. let name2 = OsStr::new("rise_against_lyrics.txt");
  331. let mut case = TestCase::new();
  332. let mnt_path = case.mnt_path();
  333. let path1 = mnt_path.join(name1);
  334. let path2 = mnt_path.join(name2);
  335. write(&path1, EXPECTED).expect("write failed");
  336. hard_link(&path1, &path2).expect("hard_link failed");
  337. remove_file(&path1).expect("remove_file failed");
  338. let actual = read(&path2).expect("read failed");
  339. assert_eq!(EXPECTED, actual);
  340. }
  341. #[test]
  342. fn hard_link_then_remove_both() {
  343. const EXPECTED: &[u8] = b"And the lives we've reclaimed";
  344. let name1 = OsStr::new("refugee_lyrics.txt");
  345. let name2 = OsStr::new("rise_against_lyrics.txt");
  346. let mut case = TestCase::new();
  347. let mnt_path = case.mnt_path();
  348. let path1 = mnt_path.join(name1);
  349. let path2 = mnt_path.join(name2);
  350. write(&path1, EXPECTED).expect("write failed");
  351. hard_link(&path1, &path2).expect("hard_link failed");
  352. remove_file(&path1).expect("remove_file on path1 failed");
  353. remove_file(&path2).expect("remove_file on path2 failed");
  354. let expected: [&OsStr; 0] = [];
  355. assert!(file_names(read_dir(&mnt_path).expect("read_dir failed")).eq(expected));
  356. }
  357. #[test]
  358. fn set_mode_bits() {
  359. const EXPECTED: u32 = libc::S_IFREG | 0o777;
  360. let mut case = TestCase::new();
  361. let file_path = case.mnt_path().join("bagobits");
  362. write(&file_path, []).expect("write failed");
  363. let original = metadata(&file_path)
  364. .expect("metadata failed")
  365. .permissions()
  366. .mode();
  367. assert_ne!(EXPECTED, original);
  368. set_permissions(&file_path, Permissions::from_mode(EXPECTED))
  369. .expect("set_permissions failed");
  370. let actual = metadata(&file_path)
  371. .expect("metadata failed")
  372. .permissions()
  373. .mode();
  374. assert_eq!(EXPECTED, actual);
  375. }
  376. #[test]
  377. fn create_directory() {
  378. const EXPECTED: &str = "etc";
  379. let mut case = TestCase::new();
  380. let mnt_path = case.mnt_path();
  381. let dir_path = mnt_path.join(EXPECTED);
  382. create_dir(&dir_path).expect("create_dir failed");
  383. let actual = file_names(read_dir(mnt_path).expect("read_dir failed"));
  384. assert!(actual.eq([EXPECTED]));
  385. }
  386. #[test]
  387. fn create_file_under_new_directory() {
  388. const DIR_NAME: &str = "etc";
  389. const FILE_NAME: &str = "file";
  390. let mut case = TestCase::new();
  391. let mnt_path = case.mnt_path();
  392. let dir_path = mnt_path.join(DIR_NAME);
  393. let file_path = dir_path.join(FILE_NAME);
  394. create_dir(&dir_path).expect("create_dir failed");
  395. write(&file_path, []).expect("write failed");
  396. let actual = file_names(read_dir(dir_path).expect("read_dir failed"));
  397. assert!(actual.eq([FILE_NAME]));
  398. }
  399. #[test]
  400. fn create_then_remove_directory() {
  401. const DIR_NAME: &str = "etc";
  402. let mut case = TestCase::new();
  403. let mnt_path = case.mnt_path();
  404. let dir_path = mnt_path.join(DIR_NAME);
  405. create_dir(&dir_path).expect("create_dir failed");
  406. remove_dir(&dir_path).expect("remove_dir failed");
  407. let actual = file_names(read_dir(&mnt_path).expect("read_dir failed"));
  408. const EMPTY: [&str; 0] = [""; 0];
  409. assert!(actual.eq(EMPTY));
  410. }
  411. #[test]
  412. fn read_only_dir_cant_create_subdir() {
  413. const DIR_NAME: &str = "etc";
  414. let mut case = TestCase::new();
  415. let dir_path = case.mnt_path().join(DIR_NAME);
  416. create_dir(&dir_path).expect("create_dir failed");
  417. set_permissions(&dir_path, Permissions::from_mode(libc::S_IFDIR | 0o444))
  418. .expect("set_permissions failed");
  419. let result = create_dir(dir_path.join("sub"));
  420. let err = result.err().expect("create_dir returned `Ok`");
  421. let os_err = err.raw_os_error().expect("raw_os_error was empty");
  422. assert_eq!(os_err, libc::EACCES);
  423. }
  424. #[test]
  425. fn read_only_dir_cant_remove_subdir() {
  426. const DIR_NAME: &str = "etc";
  427. let mut case = TestCase::new();
  428. let dir_path = case.mnt_path().join(DIR_NAME);
  429. let sub_path = dir_path.join("sub");
  430. create_dir(&dir_path).expect("create_dir failed");
  431. create_dir(&sub_path).expect("create_dir failed");
  432. set_permissions(&dir_path, Permissions::from_mode(libc::S_IFDIR | 0o444))
  433. .expect("set_permissions failed");
  434. let result = remove_dir(&sub_path);
  435. let err = result.err().expect("remove_dir returned `Ok`");
  436. let os_err = err.raw_os_error().expect("raw_os_error was empty");
  437. assert_eq!(os_err, libc::EACCES);
  438. }
  439. #[test]
  440. fn rename_file() {
  441. const FILE_NAME: &str = "parabola.txt";
  442. const EXPECTED: &[u8] = b"We are eternal all this pain is an illusion";
  443. let mut case = TestCase::new();
  444. let src_path = case.mnt_path().join(FILE_NAME);
  445. let dst_path = case.mnt_path().join("parabola_lyrics.txt");
  446. write(&src_path, EXPECTED).unwrap();
  447. rename(&src_path, &dst_path).unwrap();
  448. let actual = read(&dst_path).unwrap();
  449. assert_eq!(EXPECTED, actual)
  450. }
  451. }