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