kplib 0.26.1

Hardened KDBX database file parser
Documentation
//! Decryption of the protected values in the inner XML database of a KDBX file.
use crate::{
	crypt::ciphers::Cipher,
	format::xml_db::{ParseXmlError, entry::UnprotectError},
};
use base64::{Engine as _, engine::general_purpose as base64_engine};
use quick_xml::{Reader, events::Event};
use zeroize::Zeroizing;
/// Decrypt the content of every element marked `Protected="True"`, leaving the base64-encoded
/// plaintext in its place. Everything else is copied as it is.
///
/// All protected values are encrypted with one key stream, in the order they have in the document.
/// Deserializing loses that order: an entry's fields are collected into one list, whether they come
/// before or after its history. So this has to happen first.
pub(crate) fn unprotect_xml(xml: &[u8], inner_decryptor: &mut dyn Cipher) -> Result<Zeroizing<Vec<u8>>, ParseXmlError> {
	// The reader skips a byte order mark without counting it in its positions.
	let xml = xml.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(xml);
	// A stream cipher keeps the length, so this never grows and leaves no copies of the plaintext
	// behind.
	let mut unprotected = Zeroizing::new(Vec::with_capacity(xml.len()));
	let mut copied = 0;
	let mut reader = Reader::from_reader(xml);
	loop {
		match reader.read_event().map_err(quick_xml::DeError::from)? {
			Event::Start(element) if is_protected(&element)? => {
				let content = reader.read_to_end(element.name()).map_err(quick_xml::DeError::from)?;
				let (start, end) = (content.start as usize, content.end as usize);
				#[allow(clippy::indexing_slicing)] // the reader's positions are within the document
				let (before, value) = (&xml[copied..start], &xml[start..end]);
				let value = base64_engine::STANDARD.decode(value.trim_ascii()).map_err(UnprotectError::from)?;
				let value = Zeroizing::new(inner_decryptor.decrypt(&value).map_err(UnprotectError::from)?);
				let value = Zeroizing::new(base64_engine::STANDARD.encode(&*value));
				unprotected.extend_from_slice(before);
				unprotected.extend_from_slice(value.as_bytes());
				copied = end;
			}
			Event::Eof => break,
			_ => {}
		}
	}
	#[allow(clippy::indexing_slicing)] // the reader's positions are within the document
	unprotected.extend_from_slice(&xml[copied..]);
	Ok(unprotected)
}
/// Whether an element has the attribute `Protected="True"`, read as `cs_bool` does.
fn is_protected(element: &quick_xml::events::BytesStart<'_>) -> Result<bool, ParseXmlError> {
	let attribute = element.try_get_attribute("Protected").map_err(|e| quick_xml::DeError::from(quick_xml::Error::from(e)))?;
	Ok(attribute.is_some_and(|a| a.value.eq_ignore_ascii_case("true") || &*a.value == "1"))
}