cryptsetup: allow 'mass' reuse

This commit is contained in:
Mikaël Cluseau
2025-11-20 09:11:12 +01:00
parent ac9d7e8d9d
commit 01a0073e78
7 changed files with 78 additions and 28 deletions

View File

@ -56,27 +56,72 @@ pub async fn setup(devs: &[CryptDev]) {
.await;
}
static PREV_PW: Mutex<String> = Mutex::const_new(String::new());
struct PrevPw {
pw: String,
reuse: bool,
}
impl PrevPw {
fn is_set(&self) -> bool {
!self.pw.is_empty()
}
fn can_reuse(&self) -> bool {
self.reuse && self.is_set()
}
fn invalidate(&mut self) {
self.pw = String::new();
self.reuse = false;
}
async fn input(&mut self, prompt: impl std::fmt::Display) -> String {
if self.can_reuse() {
info!("reusing password");
self.pw.clone()
} else if self.is_set() {
let pw =
input::read_password(format!("{prompt} (\"\" reuse, \"*\" auto-reuse)? ")).await;
match pw.as_str() {
"" => self.pw.clone(),
"*" => {
self.reuse = true;
self.pw.clone()
}
_ => {
self.pw = pw.clone();
pw
}
}
} else {
let pw = loop {
let pw = input::read_password(format!("{prompt}? ")).await;
if pw.is_empty() {
error!("empty password provided!");
continue;
}
break pw;
};
self.pw = pw.clone();
pw
}
}
}
static PREV_PW: Mutex<PrevPw> = Mutex::const_new(PrevPw {
pw: String::new(),
reuse: false,
});
async fn crypt_open(crypt_dev: &str, dev_path: &str) -> Result<()> {
'open_loop: loop {
let mut prev_pw = PREV_PW.lock().await;
let prompt = if prev_pw.is_empty() {
format!("crypt password for {crypt_dev}? ")
} else {
format!("crypt password for {crypt_dev} (enter = reuse previous)? ")
};
let mut pw = input::read_password(prompt).await;
if pw.is_empty() {
pw = prev_pw.clone();
}
if pw.is_empty() {
error!("empty password provided!");
continue;
}
*prev_pw = pw.clone();
let pw = prev_pw
.input(format!("crypt password for {crypt_dev}"))
.await;
if cryptsetup(&pw, ["open", dev_path, crypt_dev]).await? {
return Ok(());
@ -107,15 +152,17 @@ async fn crypt_open(crypt_dev: &str, dev_path: &str) -> Result<()> {
}
_ => unreachable!(),
}
} else {
// device looks initialized, don't allow format
warn!("{dev_path} looks initialized, formatting not allowed from init");
}
match input::read_choice(["[r]etry", "[i]gnore"]).await {
'r' => continue 'open_loop,
'i' => return Ok(()),
_ => unreachable!(),
}
// device looks initialized, don't allow format
warn!("{dev_path} looks initialized, formatting not allowed from init");
prev_pw.invalidate();
match input::read_choice(["[r]etry", "[i]gnore"]).await {
'r' => continue 'open_loop,
'i' => return Ok(()),
_ => unreachable!(),
}
}
}