summaryrefslogtreecommitdiff
path: root/src/key.rs
blob: c432ca793198f37775741ca592708f53ab7aea81 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use std::{fmt, fs, io::{stdin, IsTerminal}};

use log::info;
use bch_bindgen::bcachefs::bch_sb_handle;
use clap::builder::PossibleValue;
use crate::c_str;
use anyhow::anyhow;

#[derive(Clone, Debug)]
pub enum KeyPolicy {
    None,
    Fail,
    Wait,
    Ask,
}

impl std::str::FromStr for KeyPolicy {
    type Err = anyhow::Error;
    fn from_str(s: &str) -> anyhow::Result<Self> {
        match s {
            ""|"none" => Ok(KeyPolicy::None),
            "fail"    => Ok(KeyPolicy::Fail),
            "wait"    => Ok(KeyPolicy::Wait),
            "ask"     => Ok(KeyPolicy::Ask),
            _         => Err(anyhow!("Invalid key policy provided")),
        }
    }
}

impl clap::ValueEnum for KeyPolicy {
    fn value_variants<'a>() -> &'a [Self] {
        &[
            KeyPolicy::None,
            KeyPolicy::Fail,
            KeyPolicy::Wait,
            KeyPolicy::Ask,
        ]
    }

    fn to_possible_value(&self) -> Option<PossibleValue> {
        Some(match self {
            Self::None => PossibleValue::new("none").alias(""),
            Self::Fail => PossibleValue::new("fail"),
            Self::Wait => PossibleValue::new("wait"),
            Self::Ask => PossibleValue::new("ask"),
        })
    }
}

impl fmt::Display for KeyPolicy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            KeyPolicy::None => write!(f, "None"),
            KeyPolicy::Fail => write!(f, "Fail"),
            KeyPolicy::Wait => write!(f, "Wait"),
            KeyPolicy::Ask => write!(f, "Ask"),
        }
    }
}

fn check_for_key(key_name: &std::ffi::CStr) -> anyhow::Result<bool> {
    use bch_bindgen::keyutils::{self, keyctl_search};
    let key_name = key_name.to_bytes_with_nul().as_ptr() as *const _;
    let key_type = c_str!("user");

    let key_id = unsafe { keyctl_search(keyutils::KEY_SPEC_USER_KEYRING, key_type, key_name, 0) };
    if key_id > 0 {
        info!("Key has become available");
        Ok(true)
    } else {
        match errno::errno().0 {
            libc::ENOKEY | libc::EKEYREVOKED => Ok(false),
            _ => Err(crate::ErrnoError(errno::errno()).into()),
        }
    }
}

fn wait_for_key(uuid: &uuid::Uuid) -> anyhow::Result<()> {
    let key_name = std::ffi::CString::new(format!("bcachefs:{}", uuid)).unwrap();
    loop {
        if check_for_key(&key_name)? {
            break Ok(());
        }

        std::thread::sleep(std::time::Duration::from_secs(1));
    }
}

fn ask_for_key(sb: &bch_sb_handle) -> anyhow::Result<()> {
    let pass = if stdin().is_terminal() {
        rpassword::prompt_password("Enter passphrase: ")?
    } else {
        let mut line = String::new();
        stdin().read_line(&mut line)?;
        line
    };
    decrypt_master_key(sb, pass)
}

const BCH_KEY_MAGIC: &str = "bch**key";
fn decrypt_master_key(sb: &bch_sb_handle, pass: String) -> anyhow::Result<()> {
    use bch_bindgen::bcachefs::{self, bch2_chacha_encrypt_key, bch_encrypted_key, bch_key};
    use byteorder::{LittleEndian, ReadBytesExt};
    use std::os::raw::c_char;

    let key_name = std::ffi::CString::new(format!("bcachefs:{}", sb.sb().uuid())).unwrap();
    if check_for_key(&key_name)? {
        return Ok(());
    }

    let bch_key_magic = BCH_KEY_MAGIC.as_bytes().read_u64::<LittleEndian>().unwrap();
    let crypt = sb.sb().crypt().unwrap();
    let pass = std::ffi::CString::new(pass.trim_end())?; // bind to keep the CString alive
    let mut output: bch_key = unsafe {
        bcachefs::derive_passphrase(
            crypt as *const _ as *mut _,
            pass.as_c_str().to_bytes_with_nul().as_ptr() as *const _,
        )
    };

    let mut key = crypt.key().clone();
    let ret = unsafe {
        bch2_chacha_encrypt_key(
            &mut output as *mut _,
            sb.sb().nonce(),
            &mut key as *mut _ as *mut _,
            std::mem::size_of::<bch_encrypted_key>() as usize,
        )
    };
    if ret != 0 {
        Err(anyhow!("chacha decryption failure"))
    } else if key.magic != bch_key_magic {
        Err(anyhow!("failed to verify the password"))
    } else {
        let key_type = c_str!("user");
        let ret = unsafe {
            bch_bindgen::keyutils::add_key(
                key_type,
                key_name.as_c_str().to_bytes_with_nul() as *const _ as *const c_char,
                &output as *const _ as *const _,
                std::mem::size_of::<bch_key>() as usize,
                bch_bindgen::keyutils::KEY_SPEC_USER_KEYRING,
            )
        };
        if ret == -1 {
            Err(anyhow!("failed to add key to keyring: {}", errno::errno()))
        } else {
            Ok(())
        }
    }
}

pub fn read_from_key_file(block_device: &bch_sb_handle, key_file: &std::path::Path) -> anyhow::Result<()> {
    // Attempts to decrypt the master key by key_file
    // Return true if decryption was successful, false otherwise
    info!("Attempting to decrypt master key for filesystem {}, using key file {}", block_device.sb().uuid(), key_file.display());
    // Read the contents of the key file into a string
    let pass = fs::read_to_string(key_file)?;
    // Call decrypt_master_key with the read string
    decrypt_master_key(block_device, pass)
}

pub fn prepare_key(block_device: &bch_sb_handle, password_policy: KeyPolicy) -> anyhow::Result<()> {
    info!("Attempting to decrypt master key for filesystem {}, using key policy {}", block_device.sb().uuid(), password_policy);
    match password_policy {
        KeyPolicy::Fail => Err(anyhow!("no key available")),
        KeyPolicy::Wait => Ok(wait_for_key(&block_device.sb().uuid())?),
        KeyPolicy::Ask => ask_for_key(block_device),
        _ => Err(anyhow!("no keyoption specified for locked filesystem")),
    }
}