Skip to main content

keepass/key/
mod.rs

1use std::io::Read;
2
3use base64::{Engine as _, engine::general_purpose as base64_engine};
4use quick_xml::{XmlVersion, encoding::EncodingError, events::Event, reader::Reader};
5use thiserror::Error;
6use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
7
8use crate::crypt::sha256_element;
9
10pub type KeyElement = Zeroizing<Vec<u8>>;
11pub type KeyElements = Vec<KeyElement>;
12
13fn parse_xml_keyfile(xml: &[u8]) -> Result<KeyElement, ParseXmlKeyFileError> {
14	let mut tag_stack = Vec::new();
15	let mut key_version: Option<String> = None;
16	let mut key_value: Option<Zeroizing<String>> = None;
17	let mut reader = Reader::from_reader(xml);
18	let mut xml_version = XmlVersion::Implicit1_0;
19	loop {
20		match reader.read_event()? {
21			Event::Eof => break,
22
23			Event::Decl(e) => {
24				xml_version = e.xml_version()?;
25			}
26
27			Event::Start(e) => {
28				tag_stack.push(e.name().as_ref().to_string());
29			}
30
31			Event::End(_) => {
32				tag_stack.pop();
33			}
34
35			Event::Text(e) => {
36				let s = Zeroizing::new(e.xml_content(xml_version).into_owned());
37
38				if tag_stack == ["KeyFile", "Meta", "Version"] {
39					key_version = Some(s.to_string());
40					continue;
41				}
42
43				if tag_stack == ["KeyFile", "Key", "Data"] {
44					key_value = Some(s);
45					continue;
46				}
47			}
48
49			_ => (),
50		}
51	}
52
53	let key_value = key_value.ok_or(ParseXmlKeyFileError::EmptyKey)?;
54
55	if key_version.as_deref() == Some("2.0") {
56		// TODO validate hash
57		let mut trimmed_key = Zeroizing::new(String::with_capacity(key_value.len()));
58		for c in key_value.trim().chars() {
59			if !matches!(c, ' ' | '\n' | '\t' | '\r') {
60				trimmed_key.push(c);
61			}
62		}
63		if let Ok(key) = hex::decode(trimmed_key.as_bytes()) {
64			return Ok(key.into());
65		}
66		return Ok(key_value.as_bytes().to_vec().into());
67	}
68
69	if let Ok(key) = base64_engine::STANDARD.decode(key_value.as_bytes()) {
70		Ok(key.into())
71	} else {
72		Ok(key_value.as_bytes().to_vec().into())
73	}
74}
75
76/// Errors that can occur when parsing an XML keyfile
77#[derive(Debug, Error)]
78#[non_exhaustive]
79pub enum ParseXmlKeyFileError {
80	/// No key data element was found in the XML keyfile
81	#[error("The XML keyfile is missing a key data element")]
82	EmptyKey,
83
84	/// A tag in the XML keyfile contains text that cannot be decoded as UTF-8
85	#[error(transparent)]
86	Encoding(#[from] EncodingError),
87
88	/// An error occurred while reading the XML keyfile
89	#[error(transparent)]
90	Xml(#[from] quick_xml::Error),
91}
92
93fn parse_keyfile(buffer: &[u8]) -> Result<KeyElement, DatabaseKeyError> {
94	// try to parse the buffer as XML, if successful, use that data instead of full file
95	if let Ok(v) = parse_xml_keyfile(buffer) {
96		return Ok(v);
97	}
98
99	// legacy binary key format
100	if buffer.len() == 32 {
101		return Ok(buffer.to_vec().into());
102	}
103
104	// legacy hex key format
105	if buffer.len() == 64
106		&& let Ok(key_bytes) = hex::decode(buffer)
107	{
108		return Ok(key_bytes.into());
109	}
110	Ok(sha256_element(&[buffer]))
111}
112
113/// A KeePass key, which might consist of a password and/or a keyfile
114#[derive(Debug, Clone, Default, PartialEq, Zeroize, ZeroizeOnDrop)]
115pub struct DatabaseKey {
116	password: Option<Zeroizing<String>>,
117	keyfile: Option<Zeroizing<Vec<u8>>>,
118}
119
120impl DatabaseKey {
121	/// Modify the database key to include a password
122	pub fn with_password(mut self, password: &str) -> Self {
123		self.password = Some(password.to_string().into());
124		self
125	}
126
127	/// Modify the database key to include a keyfile
128	///
129	/// The keyfile is only read as raw data but not parsed until the actual key elements are
130	/// requested, so errors with keyfile parsing will only be raised at that point, not when
131	/// calling this method.
132	pub fn with_keyfile(mut self, keyfile: &mut dyn Read) -> Result<Self, std::io::Error> {
133		let mut out: Zeroizing<Vec<u8>> = Vec::with_capacity(4096).into();
134		let mut chunk = Zeroizing::new([0u8; 4096]);
135		loop {
136			let n = match keyfile.read(&mut *chunk) {
137				Ok(0) => break,
138				Ok(n) => n,
139				Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
140				Err(e) => return Err(e),
141			};
142			if out.capacity() - out.len() < n {
143				let mut bigger = Zeroizing::new(Vec::with_capacity((out.len() + n).max(out.capacity() * 2)));
144				bigger.extend_from_slice(&out);
145				out = bigger; // old buffer is wiped on drop
146			}
147			out.extend_from_slice(chunk.split_at(n).0);
148		}
149		self.keyfile = Some(out);
150		Ok(self)
151	}
152
153	/// Create a new, empty database key
154	pub fn new() -> Self {
155		Default::default()
156	}
157
158	pub(crate) fn get_key_elements(&self) -> Result<KeyElements, DatabaseKeyError> {
159		let mut out = Vec::new();
160
161		if let Some(p) = &self.password {
162			out.push(sha256_element(&[p.as_bytes()]));
163		}
164
165		if let Some(ref f) = self.keyfile {
166			out.push(parse_keyfile(f)?);
167		}
168
169		if out.is_empty() {
170			return Err(DatabaseKeyError::EmptyKey);
171		}
172
173		Ok(out)
174	}
175
176	/// Returns true if the database key is not associated with any key component.
177	pub fn is_empty(&self) -> bool {
178		if self.password.is_some() || self.keyfile.is_some() {
179			return false;
180		}
181		true
182	}
183}
184
185/// Errors that can occur when working with database keys
186#[derive(Debug, Error)]
187#[non_exhaustive]
188pub enum DatabaseKeyError {
189	/// The database key contains no components, i.e. no password, keyfile or challenge-response key
190	#[error("The key contains no components")]
191	EmptyKey,
192
193	/// The database key is incorrect
194	#[error("Incorrect key")]
195	IncorrectKey,
196
197	/// An I/O error occurred while reading the keyfile
198	#[error("I/O error reading keyfile: {0}")]
199	Io(#[from] std::io::Error),
200
201	/// An error occurred while parsing the XML keyfile
202	#[error("XML error reading keyfile: {0}")]
203	Xml(#[from] quick_xml::Error),
204
205	/// An error occurred while parsing the non-XML keyfile
206	#[error("Invalid keyfile format")]
207	InvalidKeyFile,
208}
209
210#[cfg(test)]
211mod key_tests {
212	use super::{DatabaseKey, DatabaseKeyError};
213
214	struct Flaky<'a> {
215		data: &'a [u8],
216		interrupted: bool,
217	}
218
219	impl std::io::Read for Flaky<'_> {
220		fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
221			if !self.interrupted {
222				self.interrupted = true;
223				return Err(std::io::ErrorKind::Interrupted.into());
224			}
225			let n = self.data.len().min(buf.len()).min(1000);
226			let (head, tail) = self.data.split_at(n);
227			let (dst, _) = buf.split_at_mut(n);
228			dst.copy_from_slice(head);
229			self.data = tail;
230			Ok(n)
231		}
232	}
233
234	fn first(ke: &[super::KeyElement]) -> Result<&[u8], DatabaseKeyError> {
235		ke.first().map(|k| k.as_slice()).ok_or(DatabaseKeyError::EmptyKey)
236	}
237
238	#[test]
239	fn test_key() -> Result<(), DatabaseKeyError> {
240		let ke = DatabaseKey::new().with_password("asdf").get_key_elements()?;
241		assert_eq!(ke.len(), 1);
242
243		let ke = DatabaseKey::new().with_keyfile(&mut "bare-key-file".as_bytes())?.get_key_elements()?;
244		assert_eq!(ke.len(), 1);
245
246		let ke = DatabaseKey::new().with_keyfile(&mut "0123456789ABCDEF0123456789ABCDEF".as_bytes())?.get_key_elements()?;
247		assert_eq!(ke.len(), 1);
248
249		let ke = DatabaseKey::new().with_password("asdf").with_keyfile(&mut "bare-key-file".as_bytes())?.get_key_elements()?;
250		assert_eq!(ke.len(), 2);
251
252		let ke = DatabaseKey::new()
253			.with_keyfile(&mut "<KeyFile><Key><Data>0!23456789ABCDEF0123456789ABCDEF</Data></Key></KeyFile>".as_bytes())?
254			.get_key_elements()?;
255		assert_eq!(ke.len(), 1);
256
257		let ke = DatabaseKey::new()
258			.with_keyfile(&mut "<KeyFile><Key><Data>NXyYiJMHg3ls+eBmjbAjWec9lcOToJiofbhNiFMTJMw=</Data></Key></KeyFile>".as_bytes())?
259			.get_key_elements()?;
260		assert_eq!(ke.len(), 1);
261
262		let xml_keyfile_v2 = r###"
263            <?xml version="1.0" encoding="utf-8"?>
264            <KeyFile>
265                <Meta>
266                    <Version>2.0</Version>
267                </Meta>
268                <Key>
269                    <Data Hash="A65F0C2D">
270                        36057B1C 35037FD9 62257893 C0A22403
271                        EE3F8FBB 504D9981 08B821CB 00D28F89
272                    </Data>
273                </Key>
274            </KeyFile>
275        "###;
276		let ke = DatabaseKey::new().with_keyfile(&mut xml_keyfile_v2.trim().as_bytes())?.get_key_elements()?;
277		assert_eq!(ke.len(), 1);
278
279		let expected = hex::decode("36057B1C35037FD962257893C0A22403EE3F8FBB504D998108B821CB00D28F89").map_err(|_| DatabaseKeyError::InvalidKeyFile)?;
280		assert_eq!(first(&ke)?, expected.as_slice());
281
282		// other XML files will just be hashed as a "bare" keyfile
283		let ke = DatabaseKey::new().with_keyfile(&mut "<Not><A><KeyFile></KeyFile></A></Not>".as_bytes())?.get_key_elements()?;
284		assert_eq!(ke.len(), 1);
285
286		assert!(DatabaseKey { password: None, keyfile: None }.get_key_elements().is_err());
287
288		Ok(())
289	}
290
291	#[test]
292	fn test_keyfile_large_and_interrupted() -> Result<(), DatabaseKeyError> {
293		let data = vec![7u8; 10_000];
294		let ke = DatabaseKey::new().with_keyfile(&mut Flaky { data: &data, interrupted: false })?.get_key_elements()?;
295
296		assert_eq!(first(&ke)?, crate::crypt::calculate_sha256(&[data.as_slice()]).as_slice());
297
298		Ok(())
299	}
300}