]> git.sesse.net Git - bcachefs-tools-debian/blob - rust-src/src/key.rs
Update bcachefs sources to e14d7c7195 bcachefs: Compression levels
[bcachefs-tools-debian] / rust-src / src / key.rs
1 use log::{info};
2 use bch_bindgen::bcachefs::bch_sb_handle;
3 use crate::c_str;
4 use anyhow::anyhow;
5
6 #[derive(Clone, Debug)]
7 pub enum KeyLocation {
8     Fail,
9     Wait,
10     Ask,
11 }
12
13 #[derive(Clone, Debug)]
14 pub struct KeyLoc(pub Option<KeyLocation>);
15 impl std::ops::Deref for KeyLoc {
16     type Target = Option<KeyLocation>;
17     fn deref(&self) -> &Self::Target {
18         &self.0
19     }
20 }
21
22 impl std::str::FromStr for KeyLoc {
23     type Err = anyhow::Error;
24     fn from_str(s: &str) -> anyhow::Result<Self> {
25         match s {
26             ""      => Ok(KeyLoc(None)),
27             "fail"  => Ok(KeyLoc(Some(KeyLocation::Fail))),
28             "wait"  => Ok(KeyLoc(Some(KeyLocation::Wait))),
29             "ask"   => Ok(KeyLoc(Some(KeyLocation::Ask))),
30             _       => Err(anyhow!("invalid password option")),
31         }
32     }
33 }
34
35 fn check_for_key(key_name: &std::ffi::CStr) -> anyhow::Result<bool> {
36     use bch_bindgen::keyutils::{self, keyctl_search};
37     let key_name = key_name.to_bytes_with_nul().as_ptr() as *const _;
38     let key_type = c_str!("logon");
39
40     let key_id = unsafe { keyctl_search(keyutils::KEY_SPEC_USER_KEYRING, key_type, key_name, 0) };
41     if key_id > 0 {
42         info!("Key has became available");
43         Ok(true)
44     } else if errno::errno().0 != libc::ENOKEY {
45         Err(crate::ErrnoError(errno::errno()).into())
46     } else {
47         Ok(false)
48     }
49 }
50
51 fn wait_for_key(uuid: &uuid::Uuid) -> anyhow::Result<()> {
52     let key_name = std::ffi::CString::new(format!("bcachefs:{}", uuid)).unwrap();
53     loop {
54         if check_for_key(&key_name)? {
55             break Ok(());
56         }
57
58         std::thread::sleep(std::time::Duration::from_secs(1));
59     }
60 }
61
62 const BCH_KEY_MAGIC: &str = "bch**key";
63 fn ask_for_key(sb: &bch_sb_handle) -> anyhow::Result<()> {
64     use bch_bindgen::bcachefs::{self, bch2_chacha_encrypt_key, bch_encrypted_key, bch_key};
65     use byteorder::{LittleEndian, ReadBytesExt};
66     use std::os::raw::c_char;
67
68     let key_name = std::ffi::CString::new(format!("bcachefs:{}", sb.sb().uuid())).unwrap();
69     if check_for_key(&key_name)? {
70         return Ok(());
71     }
72
73     let bch_key_magic = BCH_KEY_MAGIC.as_bytes().read_u64::<LittleEndian>().unwrap();
74     let crypt = sb.sb().crypt().unwrap();
75     let pass = if atty::is(atty::Stream::Stdin) {
76         rpassword::read_password_from_tty(Some("Enter passphrase: "))?
77     } else {
78         let mut line = String::new();
79         std::io::stdin().read_line(&mut line)?;
80         line
81     };
82     let pass = std::ffi::CString::new(pass.trim_end())?; // bind to keep the CString alive
83     let mut output: bch_key = unsafe {
84         bcachefs::derive_passphrase(
85             crypt as *const _ as *mut _,
86             pass.as_c_str().to_bytes_with_nul().as_ptr() as *const _,
87         )
88     };
89
90     let mut key = crypt.key().clone();
91     let ret = unsafe {
92         bch2_chacha_encrypt_key(
93             &mut output as *mut _,
94             sb.sb().nonce(),
95             &mut key as *mut _ as *mut _,
96             std::mem::size_of::<bch_encrypted_key>() as usize,
97         )
98     };
99     if ret != 0 {
100         Err(anyhow!("chacha decryption failure"))
101     } else if key.magic != bch_key_magic {
102         Err(anyhow!("failed to verify the password"))
103     } else {
104         let key_type = c_str!("logon");
105         let ret = unsafe {
106             bch_bindgen::keyutils::add_key(
107                 key_type,
108                 key_name.as_c_str().to_bytes_with_nul() as *const _ as *const c_char,
109                 &output as *const _ as *const _,
110                 std::mem::size_of::<bch_key>() as usize,
111                 bch_bindgen::keyutils::KEY_SPEC_USER_KEYRING,
112             )
113         };
114         if ret == -1 {
115             Err(anyhow!("failed to add key to keyring: {}", errno::errno()))
116         } else {
117             Ok(())
118         }
119     }
120 }
121
122 pub fn prepare_key(sb: &bch_sb_handle, password: KeyLocation) -> anyhow::Result<()> {
123     info!("checking if key exists for filesystem {}", sb.sb().uuid());
124     match password {
125         KeyLocation::Fail => Err(anyhow!("no key available")),
126         KeyLocation::Wait => Ok(wait_for_key(&sb.sb().uuid())?),
127         KeyLocation::Ask => ask_for_key(sb),
128     }
129 }