main.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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,
  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 received started signal from `FuseDaemon`");
  237. println!("sent started signal");
  238. TestCase {
  239. temp_path_rx: rx,
  240. mnt_path: None,
  241. handle: Some(handle),
  242. }
  243. }
  244. fn mnt_path(&mut self) -> &PathBuf {
  245. self.mnt_path.get_or_insert_with(|| {
  246. let temp_path = self
  247. .temp_path_rx
  248. .recv_timeout(Duration::from_secs(1))
  249. .expect("receive failed");
  250. FuseDaemon::mnt_path(temp_path)
  251. })
  252. }
  253. fn wait(&mut self) {
  254. if let Some(handle) = self.handle.take() {
  255. handle.join().expect("join failed");
  256. }
  257. }
  258. fn unmount_and_wait(&mut self) {
  259. // If `handle` has already been taken that means `wait` has already been called. If
  260. // this thread called `wait` and subsequently became unblocked, we know that the FUSE
  261. // thread halted, which only happens when the file system is unmounted. Hence
  262. // we don't have to unmount it, nor wait for the FUSE thread.
  263. if self.handle.is_none() {
  264. return;
  265. }
  266. let mnt_path = self.mnt_path();
  267. unmount(mnt_path);
  268. self.wait();
  269. }
  270. }
  271. impl Drop for TestCase {
  272. fn drop(&mut self) {
  273. self.unmount_and_wait();
  274. }
  275. }
  276. /// Creates a new file system and mounts it at `/tmp/btfuse.<random>/mnt` so it can be
  277. /// tested manually.
  278. //#[test]
  279. #[allow(dead_code)]
  280. fn manual_test() {
  281. std::env::set_var("RUST_LOG", "debug");
  282. env_logger::Builder::from_default_env().btformat().init();
  283. let mut case = TestCase::new();
  284. case.wait();
  285. }
  286. /// Tests if the file system can be mount then unmounted successfully.
  287. #[test]
  288. fn mount_then_unmount() {
  289. let _ = TestCase::new();
  290. }
  291. #[test]
  292. fn write_read() {
  293. const EXPECTED: &[u8] =
  294. b"The paths to failure are uncountable, yet to success there is but one.";
  295. let mut case = TestCase::new();
  296. let file_path = case.mnt_path().join("file");
  297. write(&file_path, EXPECTED).expect("write failed");
  298. let actual = read(&file_path).expect("read failed");
  299. assert_eq!(EXPECTED, actual);
  300. }
  301. #[test]
  302. fn create_file_then_readdir() {
  303. const DATA: &[u8] = b"Au revoir Shoshanna!";
  304. let file_name = OsStr::new("landa_dialog.txt");
  305. let expected = [file_name];
  306. let mut case = TestCase::new();
  307. let mnt_path = case.mnt_path();
  308. let file_path = mnt_path.join(file_name);
  309. write(&file_path, DATA).expect("write failed");
  310. let first = file_names(read_dir(&mnt_path).expect("read_dir failed"));
  311. assert!(first.eq(expected));
  312. let second = file_names(read_dir(&mnt_path).expect("read_dir failed"));
  313. assert!(second.eq(expected));
  314. }
  315. #[test]
  316. fn create_then_delete_file() {
  317. const DATA: &[u8] = b"The universe is hostile, so impersonal. Devour to survive";
  318. let file_name = OsStr::new("tool_lyrics.txt");
  319. let mut case = TestCase::new();
  320. let mnt_path = case.mnt_path();
  321. let file_path = mnt_path.join(file_name);
  322. write(&file_path, DATA).expect("write failed");
  323. remove_file(&file_path).expect("remove_file failed");
  324. let expected: [&OsStr; 0] = [];
  325. assert!(file_names(read_dir(&mnt_path).expect("read_dir failed")).eq(expected))
  326. }
  327. #[test]
  328. fn hard_link_then_remove() {
  329. const EXPECTED: &[u8] = b"And the lives we've reclaimed";
  330. let name1 = OsStr::new("refugee_lyrics.txt");
  331. let name2 = OsStr::new("rise_against_lyrics.txt");
  332. let mut case = TestCase::new();
  333. let mnt_path = case.mnt_path();
  334. let path1 = mnt_path.join(name1);
  335. let path2 = mnt_path.join(name2);
  336. write(&path1, EXPECTED).expect("write failed");
  337. hard_link(&path1, &path2).expect("hard_link failed");
  338. remove_file(&path1).expect("remove_file failed");
  339. let actual = read(&path2).expect("read failed");
  340. assert_eq!(EXPECTED, actual);
  341. }
  342. #[test]
  343. fn hard_link_then_remove_both() {
  344. const EXPECTED: &[u8] = b"And the lives we've reclaimed";
  345. let name1 = OsStr::new("refugee_lyrics.txt");
  346. let name2 = OsStr::new("rise_against_lyrics.txt");
  347. let mut case = TestCase::new();
  348. let mnt_path = case.mnt_path();
  349. let path1 = mnt_path.join(name1);
  350. let path2 = mnt_path.join(name2);
  351. write(&path1, EXPECTED).expect("write failed");
  352. hard_link(&path1, &path2).expect("hard_link failed");
  353. remove_file(&path1).expect("remove_file on path1 failed");
  354. remove_file(&path2).expect("remove_file on path2 failed");
  355. let expected: [&OsStr; 0] = [];
  356. assert!(file_names(read_dir(&mnt_path).expect("read_dir failed")).eq(expected));
  357. }
  358. #[test]
  359. fn set_mode_bits() {
  360. const EXPECTED: u32 = libc::S_IFREG | 0o777;
  361. let mut case = TestCase::new();
  362. let file_path = case.mnt_path().join("bagobits");
  363. write(&file_path, []).expect("write failed");
  364. let original = metadata(&file_path)
  365. .expect("metadata failed")
  366. .permissions()
  367. .mode();
  368. assert_ne!(EXPECTED, original);
  369. set_permissions(&file_path, Permissions::from_mode(EXPECTED))
  370. .expect("set_permissions failed");
  371. let actual = metadata(&file_path)
  372. .expect("metadata failed")
  373. .permissions()
  374. .mode();
  375. assert_eq!(EXPECTED, actual);
  376. }
  377. #[test]
  378. fn create_directory() {
  379. const EXPECTED: &str = "etc";
  380. let mut case = TestCase::new();
  381. let mnt_path = case.mnt_path();
  382. let dir_path = mnt_path.join(EXPECTED);
  383. create_dir(&dir_path).expect("create_dir failed");
  384. let actual = file_names(read_dir(mnt_path).expect("read_dir failed"));
  385. assert!(actual.eq([EXPECTED]));
  386. }
  387. #[test]
  388. fn create_file_under_new_directory() {
  389. const DIR_NAME: &str = "etc";
  390. const FILE_NAME: &str = "file";
  391. let mut case = TestCase::new();
  392. let mnt_path = case.mnt_path();
  393. let dir_path = mnt_path.join(DIR_NAME);
  394. let file_path = dir_path.join(FILE_NAME);
  395. create_dir(&dir_path).expect("create_dir failed");
  396. write(&file_path, []).expect("write failed");
  397. let actual = file_names(read_dir(dir_path).expect("read_dir failed"));
  398. assert!(actual.eq([FILE_NAME]));
  399. }
  400. #[test]
  401. fn create_then_remove_directory() {
  402. const DIR_NAME: &str = "etc";
  403. let mut case = TestCase::new();
  404. let mnt_path = case.mnt_path();
  405. let dir_path = mnt_path.join(DIR_NAME);
  406. create_dir(&dir_path).expect("create_dir failed");
  407. remove_dir(&dir_path).expect("remove_dir failed");
  408. let actual = file_names(read_dir(&mnt_path).expect("read_dir failed"));
  409. const EMPTY: [&str; 0] = [""; 0];
  410. assert!(actual.eq(EMPTY));
  411. }
  412. #[test]
  413. fn read_only_dir_cant_create_subdir() {
  414. const DIR_NAME: &str = "etc";
  415. let mut case = TestCase::new();
  416. let dir_path = case.mnt_path().join(DIR_NAME);
  417. create_dir(&dir_path).expect("create_dir failed");
  418. set_permissions(&dir_path, Permissions::from_mode(libc::S_IFDIR | 0o444))
  419. .expect("set_permissions failed");
  420. let result = create_dir(dir_path.join("sub"));
  421. let err = result.err().expect("create_dir returned `Ok`");
  422. let os_err = err.raw_os_error().expect("raw_os_error was empty");
  423. assert_eq!(os_err, libc::EACCES);
  424. }
  425. #[test]
  426. fn read_only_dir_cant_remove_subdir() {
  427. const DIR_NAME: &str = "etc";
  428. let mut case = TestCase::new();
  429. let dir_path = case.mnt_path().join(DIR_NAME);
  430. let sub_path = dir_path.join("sub");
  431. create_dir(&dir_path).expect("create_dir failed");
  432. create_dir(&sub_path).expect("create_dir failed");
  433. set_permissions(&dir_path, Permissions::from_mode(libc::S_IFDIR | 0o444))
  434. .expect("set_permissions failed");
  435. let result = remove_dir(&sub_path);
  436. let err = result.err().expect("remove_dir returned `Ok`");
  437. let os_err = err.raw_os_error().expect("raw_os_error was empty");
  438. assert_eq!(os_err, libc::EACCES);
  439. }
  440. }