summaryrefslogtreecommitdiffstats
path: root/src/cryptsetup.rs
blob: 261fa2a8cb4365840a640f8c919cf40e4a66f8fb (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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
use std::process::{Command, Stdio};

use anyhow::{anyhow, Context, Result};
use log::info;
use sysinfo::{DiskExt, RefreshKind, System, SystemExt};

use crate::constant_strings_paths::{CRYPTSETUP, LSBLK};
use crate::impl_selectable_content;
use crate::mount_help::MountHelper;
use crate::password::{
    drop_sudo_privileges, execute_sudo_command, execute_sudo_command_with_password,
    reset_sudo_faillock, PasswordHolder, PasswordKind,
};
use crate::utils::{current_username, is_program_in_path};

/// Possible actions on encrypted drives
#[derive(Debug, Clone, Copy)]
pub enum BlockDeviceAction {
    MOUNT,
    UMOUNT,
}

/// get devices list from lsblk
/// Return the output of
/// ```bash
/// lsblk -l -o FSTYPE,PATH,UUID,FSVER,MOUNTPOINT,PARTLABEL
/// ```
/// as a String.
fn get_devices() -> Result<String> {
    let output = Command::new(LSBLK)
        .args(&vec!["-l", "-o", "FSTYPE,PATH,UUID,FSVER,MOUNTPOINT"])
        .stdin(Stdio::null())
        .stderr(Stdio::null())
        .output()?;
    Ok(String::from_utf8(output.stdout)?)
}

/// True iff `lsblk` and `cryptsetup` are in path.
/// Nothing here can be done without those programs.
pub fn lsblk_and_cryptsetup_installed() -> bool {
    is_program_in_path(LSBLK) && is_program_in_path(CRYPTSETUP)
}

/// Represent an encrypted device.
/// Those attributes comes from cryptsetup.
#[derive(Debug, Default, Clone)]
pub struct CryptoDevice {
    fs_type: String,
    path: String,
    uuid: String,
    fs_ver: String,
    mountpoints: Option<String>,
    device_name: Option<String>,
}

impl CryptoDevice {
    /// Parse the output of a lsblk formated line into a struct
    fn from_line(line: &str) -> Result<Self> {
        let mut crypo_device = Self::default();
        crypo_device.update_from_line(line)?;
        Ok(crypo_device)
    }

    fn update_from_line(&mut self, line: &str) -> Result<()> {
        let strings = line.split_whitespace();
        let mut params: Vec<Option<String>> = vec![None; 5];
        for (count, param) in strings.enumerate() {
            params[count] = Some(param.to_owned());
        }
        self.fs_type = params
            .remove(0)
            .context("CryptoDevice: parameter shouldn't be None")?;
        self.path = params
            .remove(0)
            .context("CryptoDevice: parameter shouldn't be None")?;
        self.uuid = params
            .remove(0)
            .context("CryptoDevice: parameter shouldn't be None")?;
        self.fs_ver = params
            .remove(0)
            .context("CryptoDevice: parameter shouldn't be None")?;
        self.mountpoints = params.remove(0);
        Ok(())
    }

    fn format_luksopen_parameters(&self) -> [String; 4] {
        [
            CRYPTSETUP.to_owned(),
            "open".to_owned(),
            self.path.clone(),
            self.uuid.clone(),
        ]
    }
    fn format_luksclose_parameters(&self) -> [String; 3] {
        [
            CRYPTSETUP.to_owned(),
            "luksClose".to_owned(),
            self.device_name
                .clone()
                .unwrap_or_else(|| self.uuid.clone()),
        ]
    }

    pub fn mount_point(&self) -> Option<String> {
        let mut system = System::new_with_specifics(RefreshKind::new().with_disks());
        system.refresh_disks_list();
        system
            .disks()
            .iter()
            .map(|d| d.mount_point())
            .filter_map(|p| p.to_str())
            .map(|s| s.to_owned())
            .find(|s| s.contains(&self.uuid))
    }

    fn set_device_name(&mut self) -> Result<()> {
        let child = Command::new(LSBLK)
            .arg("-l")
            .arg("-n")
            .arg(self.path.clone())
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()?;
        let output = child.wait_with_output()?;
        info!(
            "is opened ? output of lsblk\nstdout: {}\nstderr{}",
            String::from_utf8(output.stdout.clone())?,
            String::from_utf8(output.stderr)?
        );
        let output = String::from_utf8(output.stdout)?;
        if let Some(s) = output.lines().nth(1) {
            self.device_name = Some(
                s.split_whitespace()
                    .next()
                    .context("mapped point: shouldn't be empty")?
                    .to_owned(),
            );
        } else {
            self.device_name = None;
        }
        Ok(())
    }

    fn open_mount(&mut self, username: &str, password: &mut PasswordHolder) -> Result<bool> {
        let root_path = std::path::Path::new("/");
        self.set_device_name()?;
        if self.is_mounted() {
            Err(anyhow!("luks open mount: device is already mounted"))
        } else {
            // sudo
            let (success, _, _) =
                execute_sudo_command_with_password(&["ls", "/root"], &password.sudo()?, root_path)?;
            if !success {
                return Ok(false);
            }
            // open
            let (success, stdout, stderr) = execute_sudo_command_with_password(
                &self.format_luksopen_parameters(),
                &password.cryptsetup()?,
                root_path,
            )?;
            info!("stdout: {}\nstderr: {}", stdout, stderr);
            if !success {
                return Ok(false);
            }
            self.mount(username, password)
        }
    }

    fn umount_close(&mut self, username: &str, password: &mut PasswordHolder) -> Result<bool> {
        if !self.umount(username, password)? {
            return Ok(false);
        }
        // close
        let (success, stdout, stderr) = execute_sudo_command(&self.format_luksclose_parameters())?;
        info!("stdout: {}\nstderr: {}", stdout, stderr);
        if !success {
            return Ok(false);
        }
        // sudo -k
        let (success, stdout, stderr) = execute_sudo_command(&["-k".to_owned()])?;
        info!("stdout: {}\nstderr: {}", stdout, stderr);
        Ok(success)
    }
}

impl MountHelper for CryptoDevice {
    fn format_mkdir_parameters(&self, username: &str) -> [String; 3] {
        [
            "mkdir".to_owned(),
            "-p".to_owned(),
            format!(
                "/run/media/{}/{}",
                username,
                self.device_name
                    .clone()
                    .unwrap_or_else(|| self.uuid.clone())
            ),
        ]
    }

    fn format_mount_parameters(&mut self, username: &str) -> Vec<String> {
        vec![
            "mount".to_owned(),
            format!("/dev/mapper/{}", self.uuid),
            format!(
                "/run/media/{}/{}",
                username,