]> git.sesse.net Git - bcachefs-tools-debian/blob - src/key.rs
Disable pristine-tar option in gbp.conf, since there is no pristine-tar branch.
[bcachefs-tools-debian] / src / key.rs
1 use std::io::{stdin, IsTerminal};
2
3 use log::{info};
4 use bch_bindgen::bcachefs::bch_sb_handle;
5 use clap::builder::PossibleValue;
6 use crate::c_str;
7 use anyhow::anyhow;
8
9 #[derive(Clone, Debug)]
10 pub enum KeyLocation {
11     None,
12     Fail,
13     Wait,
14     Ask,
15 }
16
17 impl std::str::FromStr for KeyLocation {
18     type Err = anyhow::Error;
19     fn from_str(s: &str) -> anyhow::Result<Self> {
20         match s {
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")),
26         }
27     }
28 }
29
30 impl clap::ValueEnum for KeyLocation {
31     fn value_variants<'a>() -> &'a [Self] {
32         &[
33             KeyLocation::None,
34             KeyLocation::Fail,
35             KeyLocation::Wait,
36             KeyLocation::Ask,
37         ]
38     }
39
40     fn to_possible_value(&self) -> Option<PossibleValue> {
41         Some(match self {
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"),
46         })
47     }
48 }
49
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");
54
55     let key_id = unsafe { keyctl_search(keyutils::KEY_SPEC_USER_KEYRING, key_type, key_name, 0) };
56     if key_id > 0 {
57         info!("Key has became available");
58         Ok(true)
59     } else {
60         match errno::errno().0 {
61             libc::ENOKEY | libc::EKEYREVOKED => Ok(false),
62             _ => Err(crate::ErrnoError(errno::errno()).into()),
63         }
64     }
65 }
66
67 fn wait_for_key(uuid: &uuid::Uuid) -> anyhow::Result<()> {
68     let key_name = std::ffi::CString::new(format!("bcachefs:{}", uuid)).unwrap();
69     loop {
70         if check_for_key(&key_name)? {
71             break Ok(());
72         }
73
74         std::thread::sleep(std::time::Duration::from_secs(1));
75     }
76 }
77
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;
83
84     let key_name = std::ffi::CString::new(format!("bcachefs:{}", sb.sb().uuid())).unwrap();
85     if check_for_key(&key_name)? {
86         return Ok(());
87     }
88
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: ")?
93     } else {
94         let mut line = String::new();
95         stdin().read_line(&mut line)?;
96         line
97     };
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 _,
103         )
104     };
105
106     let mut key = crypt.key().clone();
107     let ret = unsafe {
108         bch2_chacha_encrypt_key(
109             &mut output as *mut _,
110             sb.sb().nonce(),
111             &mut key as *mut _ as *mut _,
112             std::mem::size_of::<bch_encrypted_key>() as usize,
113         )
114     };
115     if ret != 0 {
116         Err(anyhow!("chacha decryption failure"))
117     } else if key.magic != bch_key_magic {
118         Err(anyhow!("failed to verify the password"))
119     } else {
120         let key_type = c_str!("user");
121         let ret = unsafe {
122             bch_bindgen::keyutils::add_key(
123                 key_type,
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,
128             )
129         };
130         if ret == -1 {
131             Err(anyhow!("failed to add key to keyring: {}", errno::errno()))
132         } else {
133             Ok(())
134         }
135     }
136 }
137
138 pub fn prepare_key(sb: &bch_sb_handle, password: KeyLocation) -> anyhow::Result<()> {
139     info!("checking if key exists for filesystem {}", sb.sb().uuid());
140     match password {
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")),
145     }
146 }