ext4 com diário e entradas apagadas; LUKS1/2 e BitLocker (todas as imagens de referência do cryptsetup)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b1ac320193
commit
86344c0536
15 files changed
+2583
-80
No files matched your search
@@ -0,0 +1,470 @@
|
||||
//! BitLocker (Windows 7 em diante, inclusive BitLocker To Go): AES-CBC com ou sem difusor
|
||||
//! Elephant, e AES-XTS. Protetores: senha, chave de recuperação, chave de inicialização (.BEK),
|
||||
//! chave limpa (proteção suspensa) e chave do volume já conhecida. TPM não é suportado.
|
||||
|
||||
use super::*;
|
||||
use crate::source::{read_vec, SubSource};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
fn le16(b: &[u8], o: usize) -> usize {
|
||||
u16::from_le_bytes([b[o], b[o + 1]]) as usize
|
||||
}
|
||||
fn le32(b: &[u8], o: usize) -> u32 {
|
||||
u32::from_le_bytes(b[o..o + 4].try_into().unwrap())
|
||||
}
|
||||
fn le64(b: &[u8], o: usize) -> u64 {
|
||||
u64::from_le_bytes(b[o..o + 8].try_into().unwrap())
|
||||
}
|
||||
|
||||
const GUID_NORMAL: [u8; 16] = [0x3b, 0xd6, 0x67, 0x49, 0x29, 0x2e, 0xd8, 0x4a, 0x83, 0x99, 0xf6, 0xa3, 0x39, 0xe3, 0xd0, 0x01];
|
||||
const GUID_EOW: [u8; 16] = [0x3b, 0x4d, 0xa8, 0x92, 0x80, 0xdd, 0x0e, 0x4d, 0x9e, 0x4e, 0xb1, 0xe3, 0x28, 0x4e, 0xae, 0xd8];
|
||||
|
||||
/// Posição da tabela de deslocamentos FVE, se for BitLocker (normal ou To Go).
|
||||
fn offsets_pos(vbr: &[u8]) -> Option<usize> {
|
||||
if vbr.len() >= 11 && &vbr[3..11] == b"-FVE-FS-" {
|
||||
return Some(176);
|
||||
}
|
||||
// BitLocker To Go: parece FAT ("MSWIN4.1"), mas guarda o GUID do BitLocker no setor de boot.
|
||||
if vbr.len() >= 464 && (vbr[424..440] == GUID_NORMAL || vbr[424..440] == GUID_EOW) {
|
||||
return Some(440);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn detect(vbr: &[u8]) -> bool {
|
||||
offsets_pos(vbr).is_some()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- Elephant
|
||||
|
||||
fn rotl(x: u32, n: u32) -> u32 {
|
||||
x.rotate_left(n)
|
||||
}
|
||||
|
||||
const RA: [u32; 4] = [9, 0, 13, 0];
|
||||
const RB: [u32; 4] = [0, 10, 0, 25];
|
||||
|
||||
fn words(buf: &[u8]) -> Vec<u32> {
|
||||
buf.chunks_exact(4).map(|c| u32::from_le_bytes(c.try_into().unwrap())).collect()
|
||||
}
|
||||
|
||||
// Decifragem (ordem do dm-crypt do Linux): somas em ordem crescente.
|
||||
fn diffuser_a_decrypt(d: &mut [u32]) {
|
||||
let n = d.len();
|
||||
for _ in 0..5 {
|
||||
for i in 0..n {
|
||||
let a = d[(i + n - 2) % n];
|
||||
let b = rotl(d[(i + n - 5) % n], RA[i % 4]);
|
||||
d[i] = d[i].wrapping_add(a ^ b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn diffuser_b_decrypt(d: &mut [u32]) {
|
||||
let n = d.len();
|
||||
for _ in 0..3 {
|
||||
for i in 0..n {
|
||||
let a = d[(i + 2) % n];
|
||||
let b = rotl(d[(i + 5) % n], RB[i % 4]);
|
||||
d[i] = d[i].wrapping_add(a ^ b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Decifra um setor AES-CBC + difusor Elephant (BitLocker Vista/7 sem XTS).
|
||||
pub fn elephant_decrypt(key: &AesAny, tweak: &AesAny, buf: &mut [u8], byte_off: u64) {
|
||||
let mut iv = [0u8; 16];
|
||||
iv[..8].copy_from_slice(&byte_off.to_le_bytes());
|
||||
key.encrypt(&mut iv);
|
||||
cbc_decrypt(key, &iv, buf);
|
||||
let mut d = words(buf);
|
||||
diffuser_b_decrypt(&mut d);
|
||||
diffuser_a_decrypt(&mut d);
|
||||
for (i, w) in d.iter().enumerate() {
|
||||
buf[i * 4..i * 4 + 4].copy_from_slice(&w.to_le_bytes());
|
||||
}
|
||||
// Chave do setor: duas cifragens do deslocamento com a chave de ajuste.
|
||||
let mut k0 = [0u8; 16];
|
||||
k0[..8].copy_from_slice(&byte_off.to_le_bytes());
|
||||
let mut k1 = k0;
|
||||
k1[15] = 0x80;
|
||||
tweak.encrypt(&mut k0);
|
||||
tweak.encrypt(&mut k1);
|
||||
let mut sk = [0u8; 32];
|
||||
sk[..16].copy_from_slice(&k0);
|
||||
sk[16..].copy_from_slice(&k1);
|
||||
for (i, b) in buf.iter_mut().enumerate() {
|
||||
*b ^= sk[i % 32];
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ CCM
|
||||
|
||||
/// AES-CCM (nonce de 12 bytes, tag de 16): `blob` = tag cifrada (16) + dados cifrados.
|
||||
fn ccm_decrypt(key: &AesAny, nonce: &[u8], blob: &[u8]) -> Option<Vec<u8>> {
|
||||
if nonce.len() != 12 || blob.len() < 16 {
|
||||
return None;
|
||||
}
|
||||
let ctr = |i: u32| -> [u8; 16] {
|
||||
let mut a = [0u8; 16];
|
||||
a[0] = 2;
|
||||
a[1..13].copy_from_slice(nonce);
|
||||
a[13..16].copy_from_slice(&i.to_be_bytes()[1..]);
|
||||
key.encrypt(&mut a);
|
||||
a
|
||||
};
|
||||
let s0 = ctr(0);
|
||||
let mut tag = [0u8; 16];
|
||||
for i in 0..16 {
|
||||
tag[i] = blob[i] ^ s0[i];
|
||||
}
|
||||
let ct = &blob[16..];
|
||||
let mut pt = Vec::with_capacity(ct.len());
|
||||
for (bi, ch) in ct.chunks(16).enumerate() {
|
||||
let s = ctr(bi as u32 + 1);
|
||||
pt.extend(ch.iter().zip(s.iter()).map(|(a, b)| a ^ b));
|
||||
}
|
||||
// CBC-MAC sobre B0 + dados.
|
||||
let mut b0 = [0u8; 16];
|
||||
b0[0] = 0x3A;
|
||||
b0[1..13].copy_from_slice(nonce);
|
||||
b0[13..16].copy_from_slice(&(pt.len() as u32).to_be_bytes()[1..]);
|
||||
key.encrypt(&mut b0);
|
||||
let mut x = b0;
|
||||
for ch in pt.chunks(16) {
|
||||
for i in 0..ch.len() {
|
||||
x[i] ^= ch[i];
|
||||
}
|
||||
key.encrypt(&mut x);
|
||||
}
|
||||
(x == tag).then_some(pt)
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- chaves
|
||||
|
||||
fn stretch(initial: &[u8; 32], salt: &[u8]) -> [u8; 32] {
|
||||
let mut last = [0u8; 32];
|
||||
let mut buf = [0u8; 88];
|
||||
buf[32..64].copy_from_slice(initial);
|
||||
buf[64..80].copy_from_slice(salt);
|
||||
for i in 0u64..0x10_0000 {
|
||||
buf[..32].copy_from_slice(&last);
|
||||
buf[80..88].copy_from_slice(&i.to_le_bytes());
|
||||
last.copy_from_slice(&Sha256::digest(buf));
|
||||
}
|
||||
last
|
||||
}
|
||||
|
||||
fn password_key(pw: &str, salt: &[u8]) -> [u8; 32] {
|
||||
let utf16: Vec<u8> = pw.encode_utf16().flat_map(|u| u.to_le_bytes()).collect();
|
||||
let h1 = Sha256::digest(&utf16);
|
||||
let mut init = [0u8; 32];
|
||||
init.copy_from_slice(&Sha256::digest(h1));
|
||||
stretch(&init, salt)
|
||||
}
|
||||
|
||||
/// Chave de recuperação: 8 blocos de 6 dígitos, cada um múltiplo de 11.
|
||||
fn recovery_key(rp: &str, salt: &[u8]) -> Option<[u8; 32]> {
|
||||
let digits: String = rp.chars().filter(|c| c.is_ascii_digit()).collect();
|
||||
if digits.len() != 48 {
|
||||
return None;
|
||||
}
|
||||
let mut raw = [0u8; 16];
|
||||
for i in 0..8 {
|
||||
let n: u32 = digits[i * 6..i * 6 + 6].parse().ok()?;
|
||||
if n % 11 != 0 || n / 11 > 0xFFFF {
|
||||
return None;
|
||||
}
|
||||
raw[i * 2..i * 2 + 2].copy_from_slice(&((n / 11) as u16).to_le_bytes());
|
||||
}
|
||||
let mut init = [0u8; 32];
|
||||
init.copy_from_slice(&Sha256::digest(raw));
|
||||
Some(stretch(&init, salt))
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------- metadados
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Entry {
|
||||
etype: usize,
|
||||
vtype: usize,
|
||||
data: Vec<u8>,
|
||||
}
|
||||
|
||||
fn parse_entries(b: &[u8]) -> Vec<Entry> {
|
||||
let mut v = vec![];
|
||||
let mut o = 0;
|
||||
while o + 8 <= b.len() {
|
||||
let size = le16(b, o);
|
||||
if size < 8 || o + size > b.len() {
|
||||
break;
|
||||
}
|
||||
v.push(Entry {
|
||||
etype: le16(b, o + 2),
|
||||
vtype: le16(b, o + 4),
|
||||
data: b[o + 8..o + size].to_vec(),
|
||||
});
|
||||
o += size;
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
struct Vmk {
|
||||
protection: usize,
|
||||
nested: Vec<Entry>,
|
||||
}
|
||||
|
||||
impl Vmk {
|
||||
fn ccm(&self) -> Option<&Entry> {
|
||||
self.nested.iter().find(|e| e.vtype == 5)
|
||||
}
|
||||
fn stretch_salt(&self) -> Option<&[u8]> {
|
||||
self.nested.iter().find(|e| e.vtype == 3).filter(|e| e.data.len() >= 20).map(|e| &e.data[4..20])
|
||||
}
|
||||
}
|
||||
|
||||
struct Fve {
|
||||
method: usize,
|
||||
volume_header_offset: u64,
|
||||
volume_header_size: u64,
|
||||
encrypted_size: u64,
|
||||
meta_size: u64,
|
||||
vmks: Vec<Vmk>,
|
||||
fvek: Option<Entry>,
|
||||
}
|
||||
|
||||
fn read_fve(src: &dyn Source, offset: u64) -> Option<Fve> {
|
||||
let h = read_vec(src, offset, 64 + 48).ok()?;
|
||||
if h.len() < 112 || &h[..8] != b"-FVE-FS-" {
|
||||
return None;
|
||||
}
|
||||
let version = le16(&h, 10);
|
||||
if version != 2 {
|
||||
return None; // Vista (versão 1) não suportado
|
||||
}
|
||||
let encrypted_size = le64(&h, 16);
|
||||
let hdr_sectors = le32(&h, 28) as u64;
|
||||
let volume_header_offset = le64(&h, 56);
|
||||
let meta_size = le32(&h, 64) as usize;
|
||||
if !(48..=1 << 20).contains(&meta_size) {
|
||||
return None;
|
||||
}
|
||||
let method = le16(&h, 64 + 36);
|
||||
let all = read_vec(src, offset + 64, meta_size).ok()?;
|
||||
if all.len() < meta_size {
|
||||
return None;
|
||||
}
|
||||
let entries = parse_entries(&all[48..]);
|
||||
let mut vmks = vec![];
|
||||
let mut fvek = None;
|
||||
let (mut vh_off, mut vh_size) = (volume_header_offset, hdr_sectors * 512);
|
||||
for e in entries {
|
||||
match (e.etype, e.vtype) {
|
||||
(15, 15) if e.data.len() >= 16 => {
|
||||
vh_off = le64(&e.data, 0);
|
||||
vh_size = le64(&e.data, 8);
|
||||
}
|
||||
(2, 8) if e.data.len() > 28 => vmks.push(Vmk {
|
||||
protection: le16(&e.data, 26),
|
||||
nested: parse_entries(&e.data[28..]),
|
||||
}),
|
||||
(3, 5) => fvek = Some(e),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Some(Fve {
|
||||
method,
|
||||
volume_header_offset: vh_off,
|
||||
volume_header_size: vh_size,
|
||||
encrypted_size,
|
||||
meta_size: 0x10000,
|
||||
vmks,
|
||||
fvek,
|
||||
})
|
||||
}
|
||||
|
||||
/// Chave de um arquivo .BEK (chave de inicialização).
|
||||
fn bek_key(file: &[u8]) -> Option<Vec<u8>> {
|
||||
if file.len() < 48 {
|
||||
return None;
|
||||
}
|
||||
let es = parse_entries(&file[48..]);
|
||||
for e in &es {
|
||||
if e.vtype == 9 && e.data.len() > 24 {
|
||||
for n in parse_entries(&e.data[24..]) {
|
||||
if n.vtype == 1 && n.data.len() >= 36 {
|
||||
return Some(n.data[4..36].to_vec());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn candidate_keys(v: &Vmk, secrets: &[Secret]) -> Vec<Vec<u8>> {
|
||||
let mut out: Vec<Vec<u8>> = vec![];
|
||||
// Chave limpa: o próprio protetor guarda a chave em claro.
|
||||
if v.protection == 0 {
|
||||
for n in &v.nested {
|
||||
if n.vtype == 1 && n.data.len() >= 36 {
|
||||
out.push(n.data[4..36].to_vec());
|
||||
}
|
||||
}
|
||||
}
|
||||
for s in secrets {
|
||||
match s {
|
||||
Secret::Password(p) if v.protection == 0x2000 => {
|
||||
if let Some(salt) = v.stretch_salt() {
|
||||
out.push(password_key(p, salt).to_vec());
|
||||
}
|
||||
}
|
||||
Secret::RecoveryKey(r) if v.protection == 0x0800 => {
|
||||
if let Some(k) = v.stretch_salt().and_then(|salt| recovery_key(r, salt)) {
|
||||
out.push(k.to_vec());
|
||||
}
|
||||
}
|
||||
Secret::KeyFile(f) if v.protection == 0x0200 => {
|
||||
if let Some(k) = bek_key(f) {
|
||||
out.push(k);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn decrypt_key_entry(key: &[u8], e: &Entry) -> Option<Vec<u8>> {
|
||||
let aes = AesAny::new(key)?;
|
||||
if e.data.len() < 12 + 16 + 8 {
|
||||
return None;
|
||||
}
|
||||
let pt = ccm_decrypt(&aes, &e.data[..12], &e.data[12..])?;
|
||||
// payload = cabeçalho de entrada (8) + método (4) + chave
|
||||
(pt.len() > 12).then(|| pt[12..].to_vec())
|
||||
}
|
||||
|
||||
pub fn unlock(src: Arc<dyn Source>, secrets: &[Secret]) -> UnlockResult {
|
||||
let vbr = read_vec(src.as_ref(), 0, 512).map_err(|e| UnlockError::Corrupt(e.to_string()))?;
|
||||
if !detect(&vbr) || vbr.len() < 512 {
|
||||
return Err(UnlockError::Corrupt("não é BitLocker".into()));
|
||||
}
|
||||
let bps = le16(&vbr, 11).max(512) as u64;
|
||||
let pos = offsets_pos(&vbr).unwrap_or(176);
|
||||
// Três cópias dos metadados; usa a primeira legível.
|
||||
let mut fve = None;
|
||||
let mut meta_offsets = vec![];
|
||||
for i in 0..3 {
|
||||
let off = le64(&vbr, pos + i * 8);
|
||||
if off != 0 {
|
||||
meta_offsets.push(off);
|
||||
}
|
||||
if off != 0 && off < src.size() {
|
||||
if let Some(f) = read_fve(src.as_ref(), off) {
|
||||
fve = Some(f);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let fve = fve.ok_or_else(|| UnlockError::Unsupported("metadados FVE ilegíveis ou do Windows Vista".into()))?;
|
||||
let fvek_entry = fve.fvek.as_ref().ok_or_else(|| UnlockError::Corrupt("sem FVEK".into()))?;
|
||||
|
||||
let mut volume_key: Option<Vec<u8>> = None;
|
||||
for s in secrets {
|
||||
if let Secret::VolumeKey(k) = s {
|
||||
volume_key = Some(k.clone());
|
||||
}
|
||||
}
|
||||
let mut vmk_found: Option<Vec<u8>> = None;
|
||||
if volume_key.is_none() {
|
||||
'outer: for v in &fve.vmks {
|
||||
let Some(ccm) = v.ccm() else { continue };
|
||||
for k in candidate_keys(v, secrets) {
|
||||
if let Some(vmk) = decrypt_key_entry(&k, ccm) {
|
||||
if vmk.len() >= 32 {
|
||||
vmk_found = Some(vmk[..32].to_vec());
|
||||
break 'outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let fvek_bytes = if let Some(k) = volume_key {
|
||||
k
|
||||
} else {
|
||||
let vmk = vmk_found.ok_or(UnlockError::WrongSecret)?;
|
||||
decrypt_key_entry(&vmk, fvek_entry).ok_or_else(|| UnlockError::Corrupt("FVEK não decifra com a VMK".into()))?
|
||||
};
|
||||
let k = &fvek_bytes;
|
||||
let bad = || UnlockError::Corrupt("tamanho de chave incompatível com o método".into());
|
||||
let (cipher, name) = match fve.method {
|
||||
0x8000 | 0x8001 => {
|
||||
let n = if fve.method == 0x8000 { 16 } else { 32 };
|
||||
if k.len() < 32 + n {
|
||||
return Err(bad());
|
||||
}
|
||||
(
|
||||
SectorCipher::Elephant {
|
||||
key: AesAny::new(&k[..n]).ok_or_else(bad)?,
|
||||
tweak: AesAny::new(&k[32..32 + n]).ok_or_else(bad)?,
|
||||
},
|
||||
if n == 16 { "AES-128-CBC + difusor" } else { "AES-256-CBC + difusor" },
|
||||
)
|
||||
}
|
||||
0x8002 | 0x8003 => {
|
||||
let n = if fve.method == 0x8002 { 16 } else { 32 };
|
||||
if k.len() < n {
|
||||
return Err(bad());
|
||||
}
|
||||
let key = AesAny::new(&k[..n]).ok_or_else(bad)?;
|
||||
(SectorCipher::Cbc { key: key.clone(), iv: Iv::Eboiv(key) }, if n == 16 { "AES-128-CBC" } else { "AES-256-CBC" })
|
||||
}
|
||||
0x8004 | 0x8005 => {
|
||||
let n = if fve.method == 0x8004 { 16 } else { 32 };
|
||||
if k.len() < 2 * n {
|
||||
return Err(bad());
|
||||
}
|
||||
let iv = if bps > 512 { Iv::Unit(bps) } else { Iv::Plain64 };
|
||||
(
|
||||
SectorCipher::Xts {
|
||||
k1: AesAny::new(&k[..n]).ok_or_else(bad)?,
|
||||
k2: AesAny::new(&k[n..2 * n]).ok_or_else(bad)?,
|
||||
iv,
|
||||
},
|
||||
if n == 16 { "AES-128-XTS" } else { "AES-256-XTS" },
|
||||
)
|
||||
}
|
||||
m => return Err(UnlockError::Unsupported(format!("método de cifragem BitLocker {m:#x}"))),
|
||||
};
|
||||
let len = src.size();
|
||||
let mut cs = CryptSource::new(src.clone(), cipher, 0, len, bps);
|
||||
let mut patches = vec![];
|
||||
// Áreas de metadados FVE: o Windows não as expõe como dados.
|
||||
for off in meta_offsets {
|
||||
patches.push(Patch { at: off, len: fve.meta_size, from: 0, decrypt_from: None, zero: true });
|
||||
}
|
||||
if fve.volume_header_size > 0 && fve.volume_header_offset > 0 {
|
||||
// O início do volume original foi movido para outro lugar e cifrado lá.
|
||||
patches.push(Patch { at: fve.volume_header_offset, len: fve.volume_header_size, from: 0, decrypt_from: None, zero: true });
|
||||
patches.push(Patch {
|
||||
at: 0,
|
||||
len: fve.volume_header_size,
|
||||
from: fve.volume_header_offset,
|
||||
decrypt_from: Some(fve.volume_header_offset),
|
||||
zero: false,
|
||||
});
|
||||
}
|
||||
cs = cs.with_patches(patches);
|
||||
if fve.encrypted_size > 0 && fve.encrypted_size < len {
|
||||
cs = cs.with_plain_from(fve.encrypted_size);
|
||||
}
|
||||
Ok(Unlocked {
|
||||
source: Arc::new(cs),
|
||||
description: format!("BitLocker ({name})"),
|
||||
volume_key: Some(fvek_bytes),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn unlock_window(base: Arc<dyn Source>, start: u64, len: u64, secrets: &[Secret]) -> UnlockResult {
|
||||
unlock(Arc::new(SubSource::new(base, start, len)), secrets)
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,418 @@
|
||||
//! LUKS1 e LUKS2 (cifras AES; PBKDF2 e Argon2; hashes SHA-1/256/512 e RIPEMD-160).
|
||||
|
||||
use super::*;
|
||||
use crate::source::{read_vec, SubSource};
|
||||
use sha1::Sha1;
|
||||
use sha2::{Digest, Sha256, Sha512};
|
||||
|
||||
pub const MAGIC: &[u8; 6] = b"LUKS\xBA\xBE";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Hash {
|
||||
Sha1,
|
||||
Sha256,
|
||||
Sha512,
|
||||
Ripemd160,
|
||||
}
|
||||
|
||||
impl Hash {
|
||||
pub fn parse(s: &str) -> Option<Hash> {
|
||||
Some(match s.to_ascii_lowercase().as_str() {
|
||||
"sha1" => Hash::Sha1,
|
||||
"sha256" => Hash::Sha256,
|
||||
"sha512" => Hash::Sha512,
|
||||
"ripemd160" | "rmd160" => Hash::Ripemd160,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
pub fn size(self) -> usize {
|
||||
match self {
|
||||
Hash::Sha1 | Hash::Ripemd160 => 20,
|
||||
Hash::Sha256 => 32,
|
||||
Hash::Sha512 => 64,
|
||||
}
|
||||
}
|
||||
pub fn digest(self, parts: &[&[u8]]) -> Vec<u8> {
|
||||
fn run<D: Digest>(parts: &[&[u8]]) -> Vec<u8> {
|
||||
let mut d = D::new();
|
||||
for p in parts {
|
||||
d.update(p);
|
||||
}
|
||||
d.finalize().to_vec()
|
||||
}
|
||||
match self {
|
||||
Hash::Sha1 => run::<Sha1>(parts),
|
||||
Hash::Sha256 => run::<Sha256>(parts),
|
||||
Hash::Sha512 => run::<Sha512>(parts),
|
||||
Hash::Ripemd160 => run::<ripemd::Ripemd160>(parts),
|
||||
}
|
||||
}
|
||||
pub fn pbkdf2(self, pass: &[u8], salt: &[u8], iterations: u32, len: usize) -> Vec<u8> {
|
||||
let mut out = vec![0u8; len];
|
||||
let it = iterations.max(1);
|
||||
match self {
|
||||
Hash::Sha1 => pbkdf2::pbkdf2_hmac::<Sha1>(pass, salt, it, &mut out),
|
||||
Hash::Sha256 => pbkdf2::pbkdf2_hmac::<Sha256>(pass, salt, it, &mut out),
|
||||
Hash::Sha512 => pbkdf2::pbkdf2_hmac::<Sha512>(pass, salt, it, &mut out),
|
||||
Hash::Ripemd160 => pbkdf2::pbkdf2_hmac::<ripemd::Ripemd160>(pass, salt, it, &mut out),
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Difusão do "anti-forensic splitter".
|
||||
fn diffuse(block: &mut [u8], h: Hash) {
|
||||
let ds = h.size();
|
||||
let mut i = 0u32;
|
||||
let mut off = 0;
|
||||
while off < block.len() {
|
||||
let n = ds.min(block.len() - off);
|
||||
let d = h.digest(&[&i.to_be_bytes(), &block[off..off + n]]);
|
||||
block[off..off + n].copy_from_slice(&d[..n]);
|
||||
off += n;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Recompõe a chave a partir das `stripes` faixas (AFmerge).
|
||||
pub fn af_merge(src: &[u8], block: usize, stripes: usize, h: Hash) -> Vec<u8> {
|
||||
let mut buf = vec![0u8; block];
|
||||
for i in 0..stripes.saturating_sub(1) {
|
||||
for (b, s) in buf.iter_mut().zip(&src[i * block..(i + 1) * block]) {
|
||||
*b ^= *s;
|
||||
}
|
||||
diffuse(&mut buf, h);
|
||||
}
|
||||
let last = &src[(stripes - 1) * block..stripes * block];
|
||||
buf.iter().zip(last).map(|(a, b)| a ^ b).collect()
|
||||
}
|
||||
|
||||
/// Cifra descrita por texto como "aes-xts-plain64" ou "aes-cbc-essiv:sha256".
|
||||
pub fn parse_cipher(spec: &str, key: &[u8]) -> std::result::Result<SectorCipher, UnlockError> {
|
||||
let (alg, rest) = spec.split_once('-').ok_or_else(|| UnlockError::Unsupported(spec.into()))?;
|
||||
if !alg.eq_ignore_ascii_case("aes") {
|
||||
return Err(UnlockError::Unsupported(format!("cifra {alg} (apenas AES)")));
|
||||
}
|
||||
let (mode, ivs) = rest.split_once('-').unwrap_or((rest, "plain"));
|
||||
let bad = || UnlockError::Unsupported(format!("chave inválida para {spec}"));
|
||||
let mk_iv = |k: &[u8]| -> std::result::Result<Iv, UnlockError> {
|
||||
let ivl = ivs.to_ascii_lowercase();
|
||||
Ok(match ivl.as_str() {
|
||||
"plain64" => Iv::Plain64,
|
||||
"plain" | "plain32" => Iv::Plain32,
|
||||
"plain64be" => Iv::Plain64Be,
|
||||
s if s.starts_with("essiv:") => {
|
||||
let h = Hash::parse(&s[6..]).ok_or_else(|| UnlockError::Unsupported(spec.into()))?;
|
||||
Iv::Essiv(AesAny::new(&h.digest(&[k])).ok_or_else(bad)?)
|
||||
}
|
||||
_ => return Err(UnlockError::Unsupported(format!("IV {ivs}"))),
|
||||
})
|
||||
};
|
||||
match mode.to_ascii_lowercase().as_str() {
|
||||
"xts" => {
|
||||
if key.len() % 2 != 0 {
|
||||
return Err(bad());
|
||||
}
|
||||
let h = key.len() / 2;
|
||||
Ok(SectorCipher::Xts {
|
||||
k1: AesAny::new(&key[..h]).ok_or_else(bad)?,
|
||||
k2: AesAny::new(&key[h..]).ok_or_else(bad)?,
|
||||
iv: mk_iv(&key[..h])?,
|
||||
})
|
||||
}
|
||||
"cbc" => Ok(SectorCipher::Cbc {
|
||||
key: AesAny::new(key).ok_or_else(bad)?,
|
||||
iv: mk_iv(key)?,
|
||||
}),
|
||||
m => Err(UnlockError::Unsupported(format!("modo {m}"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn passwords(secrets: &[Secret]) -> Vec<Vec<u8>> {
|
||||
secrets
|
||||
.iter()
|
||||
.filter_map(|s| match s {
|
||||
Secret::Password(p) => Some(p.as_bytes().to_vec()),
|
||||
Secret::KeyFile(k) => Some(k.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn volume_keys(secrets: &[Secret]) -> Vec<Vec<u8>> {
|
||||
secrets
|
||||
.iter()
|
||||
.filter_map(|s| match s {
|
||||
Secret::VolumeKey(k) => Some(k.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn detect(head: &[u8]) -> bool {
|
||||
head.len() >= 8 && &head[..6] == MAGIC
|
||||
}
|
||||
|
||||
pub fn unlock(src: Arc<dyn Source>, secrets: &[Secret]) -> UnlockResult {
|
||||
let head = read_vec(src.as_ref(), 0, 8).map_err(|e| UnlockError::Corrupt(e.to_string()))?;
|
||||
if !detect(&head) {
|
||||
return Err(UnlockError::Corrupt("não é LUKS".into()));
|
||||
}
|
||||
match u16::from_be_bytes([head[6], head[7]]) {
|
||||
1 => unlock_v1(src, secrets),
|
||||
2 => unlock_v2(src, secrets),
|
||||
v => Err(UnlockError::Unsupported(format!("LUKS versão {v}"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn be32(b: &[u8], o: usize) -> u32 {
|
||||
u32::from_be_bytes(b[o..o + 4].try_into().unwrap())
|
||||
}
|
||||
|
||||
fn cstr(b: &[u8]) -> String {
|
||||
let n = b.iter().position(|&c| c == 0).unwrap_or(b.len());
|
||||
String::from_utf8_lossy(&b[..n]).to_string()
|
||||
}
|
||||
|
||||
fn unlock_v1(src: Arc<dyn Source>, secrets: &[Secret]) -> UnlockResult {
|
||||
let h = read_vec(src.as_ref(), 0, 592).map_err(|e| UnlockError::Corrupt(e.to_string()))?;
|
||||
if h.len() < 592 {
|
||||
return Err(UnlockError::Corrupt("cabeçalho LUKS1 truncado".into()));
|
||||
}
|
||||
let cipher_name = cstr(&h[8..40]);
|
||||
let cipher_mode = cstr(&h[40..72]);
|
||||
let hash = Hash::parse(&cstr(&h[72..104])).ok_or_else(|| UnlockError::Unsupported(format!("hash {}", cstr(&h[72..104]))))?;
|
||||
let payload = be32(&h, 104) as u64 * 512;
|
||||
let key_bytes = be32(&h, 108) as usize;
|
||||
let mk_digest = &h[112..132];
|
||||
let mk_salt = &h[132..164];
|
||||
let mk_iter = be32(&h, 164);
|
||||
let spec = format!("{cipher_name}-{cipher_mode}");
|
||||
if key_bytes == 0 || key_bytes > 128 {
|
||||
return Err(UnlockError::Corrupt("tamanho de chave inválido".into()));
|
||||
}
|
||||
let check = |mk: &[u8]| hash.pbkdf2(mk, mk_salt, mk_iter, 20) == mk_digest;
|
||||
let finish = |mk: Vec<u8>| -> UnlockResult {
|
||||
let cipher = parse_cipher(&spec, &mk)?;
|
||||
let len = src.size().saturating_sub(payload);
|
||||
let cs = CryptSource::new(src.clone(), cipher, payload, len, 512);
|
||||
Ok(Unlocked {
|
||||
source: Arc::new(cs),
|
||||
description: format!("LUKS1 ({spec})"),
|
||||
volume_key: Some(mk),
|
||||
})
|
||||
};
|
||||
for vk in volume_keys(secrets) {
|
||||
if vk.len() == key_bytes && check(&vk) {
|
||||
return finish(vk);
|
||||
}
|
||||
}
|
||||
let pws = passwords(secrets);
|
||||
for slot in 0..8 {
|
||||
let o = 208 + slot * 48;
|
||||
if be32(&h, o) != 0x00AC_71F3 {
|
||||
continue;
|
||||
}
|
||||
let iter = be32(&h, o + 4);
|
||||
let salt = &h[o + 8..o + 40];
|
||||
let km_off = be32(&h, o + 40) as u64 * 512;
|
||||
let stripes = be32(&h, o + 44) as usize;
|
||||
if stripes == 0 || stripes > 100_000 {
|
||||
continue;
|
||||
}
|
||||
let km_len = (key_bytes * stripes).div_ceil(512) * 512;
|
||||
let Ok(mut km) = read_vec(src.as_ref(), km_off, km_len) else { continue };
|
||||
if km.len() < km_len {
|
||||
continue;
|
||||
}
|
||||
for pw in &pws {
|
||||
let dk = hash.pbkdf2(pw, salt, iter, key_bytes);
|
||||
let cipher = parse_cipher(&spec, &dk)?;
|
||||
let mut m = km.clone();
|
||||
for (i, s) in m.chunks_exact_mut(512).enumerate() {
|
||||
cipher.decrypt_sector(s, i as u64, i as u64 * 512);
|
||||
}
|
||||
let mk = af_merge(&m, key_bytes, stripes, hash);
|
||||
if check(&mk) {
|
||||
return finish(mk);
|
||||
}
|
||||
}
|
||||
km.clear();
|
||||
}
|
||||
Err(UnlockError::WrongSecret)
|
||||
}
|
||||
|
||||
fn b64(s: &str) -> Option<Vec<u8>> {
|
||||
let mut out = vec![];
|
||||
let mut acc = 0u32;
|
||||
let mut bits = 0;
|
||||
for c in s.bytes() {
|
||||
let v = match c {
|
||||
b'A'..=b'Z' => c - b'A',
|
||||
b'a'..=b'z' => c - b'a' + 26,
|
||||
b'0'..=b'9' => c - b'0' + 52,
|
||||
b'+' => 62,
|
||||
b'/' => 63,
|
||||
b'=' | b'\n' | b'\r' => continue,
|
||||
_ => return None,
|
||||
} as u32;
|
||||
acc = (acc << 6) | v;
|
||||
bits += 6;
|
||||
if bits >= 8 {
|
||||
bits -= 8;
|
||||
out.push((acc >> bits) as u8);
|
||||
acc &= (1 << bits) - 1;
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn jstr<'a>(v: &'a serde_json::Value, k: &str) -> Option<&'a str> {
|
||||
v.get(k)?.as_str()
|
||||
}
|
||||
|
||||
/// Números no JSON do LUKS2 vêm como texto (inteiros grandes) ou número.
|
||||
fn jnum(v: &serde_json::Value, k: &str) -> Option<u64> {
|
||||
let x = v.get(k)?;
|
||||
x.as_u64().or_else(|| x.as_str()?.parse().ok())
|
||||
}
|
||||
|
||||
fn unlock_v2(src: Arc<dyn Source>, secrets: &[Secret]) -> UnlockResult {
|
||||
let h = read_vec(src.as_ref(), 0, 4096).map_err(|e| UnlockError::Corrupt(e.to_string()))?;
|
||||
if h.len() < 4096 {
|
||||
return Err(UnlockError::Corrupt("cabeçalho LUKS2 truncado".into()));
|
||||
}
|
||||
let hdr_size = u64::from_be_bytes(h[8..16].try_into().unwrap());
|
||||
if !(16384..=(4 << 20)).contains(&hdr_size) {
|
||||
return Err(UnlockError::Corrupt("tamanho de cabeçalho LUKS2 inválido".into()));
|
||||
}
|
||||
let area = read_vec(src.as_ref(), 4096, (hdr_size - 4096) as usize).map_err(|e| UnlockError::Corrupt(e.to_string()))?;
|
||||
let end = area.iter().position(|&c| c == 0).unwrap_or(area.len());
|
||||
let json: serde_json::Value = serde_json::from_slice(&area[..end]).map_err(|e| UnlockError::Corrupt(format!("JSON: {e}")))?;
|
||||
let segments = json.get("segments").and_then(|s| s.as_object()).ok_or_else(|| UnlockError::Corrupt("sem segments".into()))?;
|
||||
let (_, seg) = segments
|
||||
.iter()
|
||||
.find(|(_, s)| jstr(s, "type") == Some("crypt"))
|
||||
.ok_or_else(|| UnlockError::Unsupported("sem segmento cifrado".into()))?;
|
||||
let seg_off = jnum(seg, "offset").ok_or_else(|| UnlockError::Corrupt("offset do segmento".into()))?;
|
||||
let seg_len = match seg.get("size").and_then(|s| s.as_str()) {
|
||||
Some("dynamic") | None => src.size().saturating_sub(seg_off),
|
||||
Some(n) => n.parse().unwrap_or(0),
|
||||
};
|
||||
let seg_enc = jstr(seg, "encryption").unwrap_or("aes-xts-plain64").to_string();
|
||||
let sector = jnum(seg, "sector_size").unwrap_or(512);
|
||||
let iv_tweak = jnum(seg, "iv_tweak").unwrap_or(0);
|
||||
let digests = json.get("digests").and_then(|d| d.as_object()).ok_or_else(|| UnlockError::Corrupt("sem digests".into()))?;
|
||||
|
||||
let check = |vk: &[u8]| -> bool {
|
||||
for (_, d) in digests {
|
||||
if jstr(d, "type") != Some("pbkdf2") {
|
||||
continue;
|
||||
}
|
||||
let (Some(hash), Some(salt), Some(want), Some(it)) = (
|
||||
jstr(d, "hash").and_then(Hash::parse),
|
||||
jstr(d, "salt").and_then(b64),
|
||||
jstr(d, "digest").and_then(b64),
|
||||
jnum(d, "iterations"),
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
if hash.pbkdf2(vk, &salt, it as u32, want.len()) == want {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
};
|
||||
let finish = |vk: Vec<u8>| -> UnlockResult {
|
||||
let cipher = parse_cipher(&seg_enc, &vk)?;
|
||||
let cs = CryptSource::new(src.clone(), cipher, seg_off, seg_len, sector).with_iv_tweak(iv_tweak);
|
||||
Ok(Unlocked {
|
||||
source: Arc::new(cs),
|
||||
description: format!("LUKS2 ({seg_enc})"),
|
||||
volume_key: Some(vk),
|
||||
})
|
||||
};
|
||||
for vk in volume_keys(secrets) {
|
||||
if check(&vk) {
|
||||
return finish(vk);
|
||||
}
|
||||
}
|
||||
let pws = passwords(secrets);
|
||||
let slots = json.get("keyslots").and_then(|d| d.as_object()).ok_or_else(|| UnlockError::Corrupt("sem keyslots".into()))?;
|
||||
let mut unsupported: Option<String> = None;
|
||||
for (_, slot) in slots {
|
||||
if jstr(slot, "type") != Some("luks2") {
|
||||
continue;
|
||||
}
|
||||
let key_size = jnum(slot, "key_size").unwrap_or(0) as usize;
|
||||
let af = slot.get("af");
|
||||
let stripes = af.and_then(|a| jnum(a, "stripes")).unwrap_or(4000) as usize;
|
||||
let af_hash = af.and_then(|a| jstr(a, "hash")).and_then(Hash::parse).unwrap_or(Hash::Sha256);
|
||||
let ar = slot.get("area");
|
||||
let (Some(a_off), Some(a_size)) = (ar.and_then(|a| jnum(a, "offset")), ar.and_then(|a| jnum(a, "size"))) else { continue };
|
||||
let a_enc = ar.and_then(|a| jstr(a, "encryption")).unwrap_or("aes-xts-plain64");
|
||||
let a_ksize = ar.and_then(|a| jnum(a, "key_size")).unwrap_or(64) as usize;
|
||||
let kdf = slot.get("kdf");
|
||||
let Some(kdf) = kdf else { continue };
|
||||
let salt = jstr(kdf, "salt").and_then(b64).unwrap_or_default();
|
||||
let km_len = (key_size * stripes).div_ceil(512) * 512;
|
||||
if key_size == 0 || stripes == 0 || km_len as u64 > a_size {
|
||||
continue;
|
||||
}
|
||||
let Ok(km) = read_vec(src.as_ref(), a_off, km_len) else { continue };
|
||||
if km.len() < km_len {
|
||||
continue;
|
||||
}
|
||||
for pw in &pws {
|
||||
let dk: Vec<u8> = match jstr(kdf, "type") {
|
||||
Some("pbkdf2") => {
|
||||
let hh = jstr(kdf, "hash").and_then(Hash::parse).unwrap_or(Hash::Sha256);
|
||||
hh.pbkdf2(pw, &salt, jnum(kdf, "iterations").unwrap_or(1000) as u32, a_ksize)
|
||||
}
|
||||
Some(t @ ("argon2i" | "argon2id")) => {
|
||||
let alg = if t == "argon2i" { argon2::Algorithm::Argon2i } else { argon2::Algorithm::Argon2id };
|
||||
let params = match argon2::Params::new(
|
||||
jnum(kdf, "memory").unwrap_or(65536) as u32,
|
||||
jnum(kdf, "time").unwrap_or(4) as u32,
|
||||
jnum(kdf, "cpus").unwrap_or(1) as u32,
|
||||
Some(a_ksize),
|
||||
) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
unsupported = Some(format!("parâmetros Argon2: {e}"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut out = vec![0u8; a_ksize];
|
||||
if argon2::Argon2::new(alg, argon2::Version::V0x13, params).hash_password_into(pw, &salt, &mut out).is_err() {
|
||||
continue;
|
||||
}
|
||||
out
|
||||
}
|
||||
Some(t) => {
|
||||
unsupported = Some(format!("KDF {t}"));
|
||||
continue;
|
||||
}
|
||||
None => continue,
|
||||
};
|
||||
let cipher = parse_cipher(a_enc, &dk)?;
|
||||
let mut m = km.clone();
|
||||
for (i, s) in m.chunks_exact_mut(512).enumerate() {
|
||||
cipher.decrypt_sector(s, i as u64, i as u64 * 512);
|
||||
}
|
||||
let vk = af_merge(&m, key_size, stripes, af_hash);
|
||||
if check(&vk) {
|
||||
return finish(vk);
|
||||
}
|
||||
}
|
||||
}
|
||||
match unsupported {
|
||||
Some(u) => Err(UnlockError::Unsupported(u)),
|
||||
None => Err(UnlockError::WrongSecret),
|
||||
}
|
||||
}
|
||||
|
||||
/// Atalho: abre uma janela da origem como LUKS.
|
||||
pub fn unlock_window(base: Arc<dyn Source>, start: u64, len: u64, secrets: &[Secret]) -> UnlockResult {
|
||||
unlock(Arc::new(SubSource::new(base, start, len)), secrets)
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
//! Cifras de disco (somente leitura) e desbloqueio de volumes cifrados.
|
||||
//!
|
||||
//! O volume desbloqueado é exposto como uma `Source` comum: o restante do Guará
|
||||
//! (varredura, recuperação) enxerga o sistema de arquivos em claro, sem saber
|
||||
//! que existe cifra por baixo.
|
||||
|
||||
pub mod bitlocker;
|
||||
pub mod filevault;
|
||||
pub mod luks;
|
||||
|
||||
use crate::source::Source;
|
||||
use aes::cipher::generic_array::GenericArray;
|
||||
use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit};
|
||||
use aes::{Aes128, Aes192, Aes256};
|
||||
use std::io;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// AES com tamanho de chave escolhido em tempo de execução.
|
||||
#[derive(Clone)]
|
||||
pub enum AesAny {
|
||||
A128(Aes128),
|
||||
A192(Aes192),
|
||||
A256(Aes256),
|
||||
}
|
||||
|
||||
impl AesAny {
|
||||
pub fn new(key: &[u8]) -> Option<Self> {
|
||||
Some(match key.len() {
|
||||
16 => AesAny::A128(Aes128::new_from_slice(key).ok()?),
|
||||
24 => AesAny::A192(Aes192::new_from_slice(key).ok()?),
|
||||
32 => AesAny::A256(Aes256::new_from_slice(key).ok()?),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
pub fn encrypt(&self, b: &mut [u8; 16]) {
|
||||
let g = GenericArray::from_mut_slice(b);
|
||||
match self {
|
||||
AesAny::A128(c) => c.encrypt_block(g),
|
||||
AesAny::A192(c) => c.encrypt_block(g),
|
||||
AesAny::A256(c) => c.encrypt_block(g),
|
||||
}
|
||||
}
|
||||
pub fn decrypt(&self, b: &mut [u8; 16]) {
|
||||
let g = GenericArray::from_mut_slice(b);
|
||||
match self {
|
||||
AesAny::A128(c) => c.decrypt_block(g),
|
||||
AesAny::A192(c) => c.decrypt_block(g),
|
||||
AesAny::A256(c) => c.decrypt_block(g),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn xor16(a: &mut [u8; 16], b: &[u8]) {
|
||||
for i in 0..16 {
|
||||
a[i] ^= b[i];
|
||||
}
|
||||
}
|
||||
|
||||
/// Como o vetor de inicialização de cada setor é calculado.
|
||||
#[derive(Clone)]
|
||||
pub enum Iv {
|
||||
/// Número do setor (de 512 bytes) em 64 bits little-endian.
|
||||
Plain64,
|
||||
/// Número do setor em 32 bits little-endian.
|
||||
Plain32,
|
||||
Plain64Be,
|
||||
/// ESSIV: AES(SHA-256(chave), setor).
|
||||
Essiv(AesAny),
|
||||
/// Número da unidade de dados (setor de `usize` bytes) em 64 bits little-endian.
|
||||
Unit(u64),
|
||||
/// BitLocker (Windows 10 1511+): AES(chave, offset em bytes).
|
||||
Eboiv(AesAny),
|
||||
/// BitLocker CBC com difusor Elephant: IV = AES(chave, offset em bytes).
|
||||
Bitlocker(AesAny),
|
||||
}
|
||||
|
||||
impl Iv {
|
||||
fn make(&self, sector_512: u64, byte_off: u64) -> [u8; 16] {
|
||||
let mut iv = [0u8; 16];
|
||||
match self {
|
||||
Iv::Plain64 => iv[..8].copy_from_slice(§or_512.to_le_bytes()),
|
||||
Iv::Plain32 => iv[..4].copy_from_slice(&(sector_512 as u32).to_le_bytes()),
|
||||
Iv::Plain64Be => iv[8..].copy_from_slice(§or_512.to_be_bytes()),
|
||||
Iv::Unit(u) => iv[..8].copy_from_slice(&(byte_off / u).to_le_bytes()),
|
||||
Iv::Essiv(k) => {
|
||||
iv[..8].copy_from_slice(§or_512.to_le_bytes());
|
||||
k.encrypt(&mut iv);
|
||||
}
|
||||
Iv::Eboiv(k) | Iv::Bitlocker(k) => {
|
||||
iv[..8].copy_from_slice(&byte_off.to_le_bytes());
|
||||
k.encrypt(&mut iv);
|
||||
}
|
||||
}
|
||||
iv
|
||||
}
|
||||
}
|
||||
|
||||
/// Cifra aplicada setor a setor.
|
||||
#[derive(Clone)]
|
||||
pub enum SectorCipher {
|
||||
Xts { k1: AesAny, k2: AesAny, iv: Iv },
|
||||
Cbc { key: AesAny, iv: Iv },
|
||||
/// BitLocker AES-CBC com difusor Elephant (chave de dados + chave de ajuste).
|
||||
Elephant { key: AesAny, tweak: AesAny },
|
||||
}
|
||||
|
||||
fn gf_double(t: &mut [u8; 16]) {
|
||||
let mut carry = 0u8;
|
||||
for b in t.iter_mut() {
|
||||
let next = *b >> 7;
|
||||
*b = (*b << 1) | carry;
|
||||
carry = next;
|
||||
}
|
||||
if carry != 0 {
|
||||
t[0] ^= 0x87;
|
||||
}
|
||||
}
|
||||
|
||||
impl SectorCipher {
|
||||
/// Decifra um setor no lugar. `sector_512` conta setores de 512 bytes; `byte_off` é a posição
|
||||
/// em bytes relativa ao início dos dados cifrados.
|
||||
pub fn decrypt_sector(&self, buf: &mut [u8], sector_512: u64, byte_off: u64) {
|
||||
match self {
|
||||
SectorCipher::Xts { k1, k2, iv } => {
|
||||
let mut t = iv.make(sector_512, byte_off);
|
||||
k2.encrypt(&mut t);
|
||||
for ch in buf.chunks_exact_mut(16) {
|
||||
let mut b = [0u8; 16];
|
||||
b.copy_from_slice(ch);
|
||||
xor16(&mut b, &t);
|
||||
k1.decrypt(&mut b);
|
||||
xor16(&mut b, &t);
|
||||
ch.copy_from_slice(&b);
|
||||
gf_double(&mut t);
|
||||
}
|
||||
}
|
||||
SectorCipher::Cbc { key, iv } => {
|
||||
cbc_decrypt(key, &iv.make(sector_512, byte_off), buf);
|
||||
}
|
||||
SectorCipher::Elephant { key, tweak } => {
|
||||
bitlocker::elephant_decrypt(key, tweak, buf, byte_off);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cbc_decrypt(key: &AesAny, iv: &[u8; 16], buf: &mut [u8]) {
|
||||
let mut prev = *iv;
|
||||
for ch in buf.chunks_exact_mut(16) {
|
||||
let mut c = [0u8; 16];
|
||||
c.copy_from_slice(ch);
|
||||
let mut b = c;
|
||||
key.decrypt(&mut b);
|
||||
xor16(&mut b, &prev);
|
||||
ch.copy_from_slice(&b);
|
||||
prev = c;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cbc_encrypt(key: &AesAny, iv: &[u8; 16], buf: &mut [u8]) {
|
||||
let mut prev = *iv;
|
||||
for ch in buf.chunks_exact_mut(16) {
|
||||
let mut b = [0u8; 16];
|
||||
b.copy_from_slice(ch);
|
||||
xor16(&mut b, &prev);
|
||||
key.encrypt(&mut b);
|
||||
ch.copy_from_slice(&b);
|
||||
prev = b;
|
||||
}
|
||||
}
|
||||
|
||||
/// Volume cifrado visto em claro: `len` bytes que começam em `data_offset` na origem.
|
||||
pub struct CryptSource {
|
||||
inner: Arc<dyn Source>,
|
||||
cipher: SectorCipher,
|
||||
data_offset: u64,
|
||||
len: u64,
|
||||
sector: u64,
|
||||
/// Setores antes deste limite estão em claro (BitLocker parcialmente cifrado) ou
|
||||
/// são cobertos por uma cópia (os primeiros setores do BitLocker).
|
||||
patches: Vec<Patch>,
|
||||
/// A partir deste byte (relativo aos dados) o conteúdo ainda não foi cifrado.
|
||||
plain_from: u64,
|
||||
/// Somado ao número do setor no cálculo do IV (iv_tweak do LUKS2).
|
||||
iv_tweak: u64,
|
||||
}
|
||||
|
||||
/// Trecho do volume lido de outro lugar da origem (BitLocker move o início do volume).
|
||||
#[derive(Clone)]
|
||||
pub struct Patch {
|
||||
/// Início no volume em claro.
|
||||
pub at: u64,
|
||||
pub len: u64,
|
||||
/// Onde estão os dados, na origem, já em claro.
|
||||
pub from: u64,
|
||||
/// Se os bytes de origem precisam ser decifrados (usando a posição `from_crypt`).
|
||||
pub decrypt_from: Option<u64>,
|
||||
/// Devolve zeros (áreas de metadados do BitLocker).
|
||||
pub zero: bool,
|
||||
}
|
||||
|
||||
impl CryptSource {
|
||||
pub fn new(inner: Arc<dyn Source>, cipher: SectorCipher, data_offset: u64, len: u64, sector: u64) -> Self {
|
||||
let sector = sector.max(512);
|
||||
Self {
|
||||
inner,
|
||||
cipher,
|
||||
data_offset,
|
||||
len: len / sector * sector,
|
||||
sector,
|
||||
patches: vec![],
|
||||
plain_from: u64::MAX,
|
||||
iv_tweak: 0,
|
||||
}
|
||||
}
|
||||
pub fn with_patches(mut self, p: Vec<Patch>) -> Self {
|
||||
self.patches = p;
|
||||
self
|
||||
}
|
||||
pub fn with_iv_tweak(mut self, t: u64) -> Self {
|
||||
self.iv_tweak = t;
|
||||
self
|
||||
}
|
||||
pub fn with_plain_from(mut self, off: u64) -> Self {
|
||||
self.plain_from = off;
|
||||
self
|
||||
}
|
||||
|
||||
fn read_sector_plain(&self, rel: u64, out: &mut [u8]) -> io::Result<()> {
|
||||
// `rel` alinhado ao setor; `out.len() == sector`.
|
||||
for p in &self.patches {
|
||||
if rel >= p.at && rel < p.at + p.len {
|
||||
if p.zero {
|
||||
out.fill(0);
|
||||
return Ok(());
|
||||
}
|
||||
let src_off = p.from + (rel - p.at);
|
||||
crate::source::read_exact_at(self.inner.as_ref(), self.data_offset + src_off, out)?;
|
||||
if let Some(pos) = p.decrypt_from {
|
||||
let r = pos + (rel - p.at);
|
||||
self.cipher.decrypt_sector(out, r / 512, r);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
crate::source::read_exact_at(self.inner.as_ref(), self.data_offset + rel, out)?;
|
||||
if rel < self.plain_from {
|
||||
self.cipher.decrypt_sector(out, rel / 512 + self.iv_tweak, rel);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Source for CryptSource {
|
||||
fn size(&self) -> u64 {
|
||||
self.len
|
||||
}
|
||||
fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<usize> {
|
||||
if offset >= self.len || buf.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let want = buf.len().min((self.len - offset) as usize);
|
||||
let s = self.sector;
|
||||
let mut done = 0usize;
|
||||
let mut tmp = vec![0u8; s as usize];
|
||||
while done < want {
|
||||
let pos = offset + done as u64;
|
||||
let rel = pos / s * s;
|
||||
let within = (pos - rel) as usize;
|
||||
let n = (s as usize - within).min(want - done);
|
||||
self.read_sector_plain(rel, &mut tmp)?;
|
||||
buf[done..done + n].copy_from_slice(&tmp[within..within + n]);
|
||||
done += n;
|
||||
}
|
||||
Ok(done)
|
||||
}
|
||||
}
|
||||
|
||||
/// Algo que o usuário fornece para abrir um volume.
|
||||
#[derive(Clone)]
|
||||
pub enum Secret {
|
||||
Password(String),
|
||||
/// Chave de recuperação numérica do BitLocker (8 grupos de 6 dígitos).
|
||||
RecoveryKey(String),
|
||||
/// Conteúdo de um arquivo de chave (.BEK do BitLocker, keyfile do LUKS).
|
||||
KeyFile(Vec<u8>),
|
||||
/// Chave do volume já conhecida (FVEK/master key).
|
||||
VolumeKey(Vec<u8>),
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Secret {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Secret::Password(_) => "Secret::Password(..)",
|
||||
Secret::RecoveryKey(_) => "Secret::RecoveryKey(..)",
|
||||
Secret::KeyFile(_) => "Secret::KeyFile(..)",
|
||||
Secret::VolumeKey(_) => "Secret::VolumeKey(..)",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum UnlockError {
|
||||
/// Nenhuma das senhas/chaves abriu o volume.
|
||||
WrongSecret,
|
||||
Unsupported(String),
|
||||
Corrupt(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for UnlockError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
UnlockError::WrongSecret => write!(f, "senha ou chave incorreta"),
|
||||
UnlockError::Unsupported(s) => write!(f, "não suportado: {s}"),
|
||||
UnlockError::Corrupt(s) => write!(f, "cabeçalho inválido: {s}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<UnlockError> for crate::Error {
|
||||
fn from(e: UnlockError) -> Self {
|
||||
crate::Error::msg(e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Volume aberto.
|
||||
pub struct Unlocked {
|
||||
pub source: Arc<dyn Source>,
|
||||
pub description: String,
|
||||
/// Chave do volume (para reabrir sem a senha, se o usuário permitir guardá-la).
|
||||
pub volume_key: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
pub type UnlockResult = std::result::Result<Unlocked, UnlockError>;
|
||||
|
||||
pub fn to_hex(b: &[u8]) -> String {
|
||||
b.iter().map(|x| format!("{x:02x}")).collect()
|
||||
}
|
||||
|
||||
pub fn from_hex(s: &str) -> Option<Vec<u8>> {
|
||||
let s = s.trim();
|
||||
if s.len() % 2 != 0 {
|
||||
return None;
|
||||
}
|
||||
(0..s.len() / 2).map(|i| u8::from_str_radix(&s[i * 2..i * 2 + 2], 16).ok()).collect()
|
||||
}
|
||||
Reference in new issue
Block a user