1 use std::io::{stdin, IsTerminal};
4 use bch_bindgen::bcachefs::bch_sb_handle;
5 use clap::builder::PossibleValue;
9 #[derive(Clone, Debug)]
10 pub enum KeyLocation {
17 impl std::str::FromStr for KeyLocation {
18 type Err = anyhow::Error;
19 fn from_str(s: &str) -> anyhow::Result<Self> {
21 ""|"none" => Ok(KeyLocation::None),
22 "fail" => Ok(KeyLocation::Fail),
23 "wait" => Ok(KeyLocation::Wait),
24 "ask" => Ok(KeyLocation::Ask),
25 _ => Err(anyhow!("invalid password option")),
30 impl clap::ValueEnum for KeyLocation {
31 fn value_variants<'a>() -> &'a [Self] {
40 fn to_possible_value(&self) -> Option<PossibleValue> {
42 Self::None => PossibleValue::new("none").alias(""),
43 Self::Fail => PossibleValue::new("fail"),
44 Self::Wait => PossibleValue::new("wait"),
45 Self::Ask => PossibleValue::new("ask"),
50 fn check_for_key(key_name: &std::ffi::CStr) -> anyhow::Result<bool> {
51 use bch_bindgen::keyutils::{self, keyctl_search};
52 let key_name = key_name.to_bytes_with_nul().as_ptr() as *const _;
53 let key_type = c_str!("user");
55 let key_id = unsafe { keyctl_search(keyutils::KEY_SPEC_USER_KEYRING, key_type, key_name, 0) };
57 info!("Key has became available");
60 match errno::errno().0 {
61 libc::ENOKEY | libc::EKEYREVOKED => Ok(false),
62 _ => Err(crate::ErrnoError(errno::errno()).into()),
67 fn wait_for_key(uuid: &uuid::Uuid) -> anyhow::Result<()> {
68 let key_name = std::ffi::CString::new(format!("bcachefs:{}", uuid)).unwrap();
70 if check_for_key(&key_name)? {
74 std::thread::sleep(std::time::Duration::from_secs(1));
78 const BCH_KEY_MAGIC: &str = "bch**key";
79 fn ask_for_key(sb: &bch_sb_handle) -> anyhow::Result<()> {
80 use bch_bindgen::bcachefs::{self, bch2_chacha_encrypt_key, bch_encrypted_key, bch_key};
81 use byteorder::{LittleEndian, ReadBytesExt};
82 use std::os::raw::c_char;
84 let key_name = std::ffi::CString::new(format!("bcachefs:{}", sb.sb().uuid())).unwrap();
85 if check_for_key(&key_name)? {
89 let bch_key_magic = BCH_KEY_MAGIC.as_bytes().read_u64::<LittleEndian>().unwrap();
90 let crypt = sb.sb().crypt().unwrap();
91 let pass = if stdin().is_terminal() {
92 rpassword::prompt_password("Enter passphrase: ")?
94 let mut line = String::new();
95 stdin().read_line(&mut line)?;
98 let pass = std::ffi::CString::new(pass.trim_end())?; // bind to keep the CString alive
99 let mut output: bch_key = unsafe {
100 bcachefs::derive_passphrase(
101 crypt as *const _ as *mut _,
102 pass.as_c_str().to_bytes_with_nul().as_ptr() as *const _,
106 let mut key = crypt.key().clone();
108 bch2_chacha_encrypt_key(
109 &mut output as *mut _,
111 &mut key as *mut _ as *mut _,
112 std::mem::size_of::<bch_encrypted_key>() as usize,
116 Err(anyhow!("chacha decryption failure"))
117 } else if key.magic != bch_key_magic {
118 Err(anyhow!("failed to verify the password"))
120 let key_type = c_str!("user");
122 bch_bindgen::keyutils::add_key(
124 key_name.as_c_str().to_bytes_with_nul() as *const _ as *const c_char,
125 &output as *const _ as *const _,
126 std::mem::size_of::<bch_key>() as usize,
127 bch_bindgen::keyutils::KEY_SPEC_USER_KEYRING,
131 Err(anyhow!("failed to add key to keyring: {}", errno::errno()))
138 pub fn prepare_key(sb: &bch_sb_handle, password: KeyLocation) -> anyhow::Result<()> {
139 info!("checking if key exists for filesystem {}", sb.sb().uuid());
141 KeyLocation::Fail => Err(anyhow!("no key available")),
142 KeyLocation::Wait => Ok(wait_for_key(&sb.sb().uuid())?),
143 KeyLocation::Ask => ask_for_key(sb),
144 _ => Err(anyhow!("no keyoption specified for locked filesystem")),