]> git.sesse.net Git - bcachefs-tools-debian/blob - rust-src/mount/src/key.rs
New upstream release
[bcachefs-tools-debian] / rust-src / mount / src / key.rs
1 use tracing::info;
2
3 fn check_for_key(key_name: &std::ffi::CStr) -> anyhow::Result<bool> {
4         use bch_bindgen::keyutils::{self, keyctl_search};
5         let key_name = key_name.to_bytes_with_nul().as_ptr() as *const _;
6         let key_type = c_str!("logon");
7
8         let key_id = unsafe { keyctl_search(keyutils::KEY_SPEC_USER_KEYRING, key_type, key_name, 0) };
9         if key_id > 0 {
10                 info!("Key has became avaiable");
11                 Ok(true)
12         } else if errno::errno().0 != libc::ENOKEY {
13                 Err(crate::ErrnoError(errno::errno()).into())
14         } else {
15                 Ok(false)
16         }
17 }
18
19 fn wait_for_key(uuid: &uuid::Uuid) -> anyhow::Result<()> {
20         let key_name = std::ffi::CString::new(format!("bcachefs:{}", uuid)).unwrap();
21         loop {
22                 if check_for_key(&key_name)? {
23                         break Ok(());
24                 }
25
26                 std::thread::sleep(std::time::Duration::from_secs(1));
27         }
28 }
29
30 const BCH_KEY_MAGIC: &str = "bch**key";
31 use crate::filesystem::FileSystem;
32 fn ask_for_key(fs: &FileSystem) -> anyhow::Result<()> {
33         use anyhow::anyhow;
34         use byteorder::{LittleEndian, ReadBytesExt};
35         use bch_bindgen::bcachefs::{self, bch2_chacha_encrypt_key, bch_encrypted_key, bch_key};
36         use std::os::raw::c_char;
37
38         let key_name = std::ffi::CString::new(format!("bcachefs:{}", fs.uuid())).unwrap();
39         if check_for_key(&key_name)? {
40                 return Ok(());
41         }
42
43         let bch_key_magic = BCH_KEY_MAGIC.as_bytes().read_u64::<LittleEndian>().unwrap();
44         let crypt = fs.sb().sb().crypt().unwrap();
45         let pass = rpassword::read_password_from_tty(Some("Enter passphrase: "))?;
46         let pass = std::ffi::CString::new(pass.trim_end())?; // bind to keep the CString alive
47         let mut output: bch_key = unsafe {
48                 bcachefs::derive_passphrase(
49                         crypt as *const _ as *mut _,
50                         pass.as_c_str().to_bytes_with_nul().as_ptr() as *const _,
51                 )
52         };
53
54         let mut key = crypt.key().clone();
55         let ret = unsafe {
56                 bch2_chacha_encrypt_key(
57                         &mut output as *mut _,
58                         fs.sb().sb().nonce(),
59                         &mut key as *mut _ as *mut _,
60                         std::mem::size_of::<bch_encrypted_key>() as u64,
61                 )
62         };
63         if ret != 0 {
64                 Err(anyhow!("chacha decryption failure"))
65         } else if key.magic != bch_key_magic {
66                 Err(anyhow!("failed to verify the password"))
67         } else {
68                 let key_type = c_str!("logon");
69                 let ret = unsafe {
70                         bch_bindgen::keyutils::add_key(
71                                 key_type,
72                                 key_name.as_c_str().to_bytes_with_nul() as *const _ as *const c_char,
73                                 &output as *const _ as *const _,
74                                 std::mem::size_of::<bch_key>() as u64,
75                                 bch_bindgen::keyutils::KEY_SPEC_USER_KEYRING,
76                         )
77                 };
78                 if ret == -1 {
79                         Err(anyhow!("failed to add key to keyring: {}", errno::errno()))
80                 } else {
81                         Ok(())
82                 }
83         }
84 }
85
86 #[tracing_attributes::instrument]
87 pub fn prepare_key(fs: &FileSystem, password: crate::KeyLocation) -> anyhow::Result<()> {
88         use crate::KeyLocation::*;
89         use anyhow::anyhow;
90
91         tracing::info!(msg = "checking if key exists for filesystem");
92         match password {
93                 Fail => Err(anyhow!("no key available")),
94                 Wait => Ok(wait_for_key(fs.uuid())?),
95                 Ask => ask_for_key(fs),
96         }
97 }