kplib 0.26.1

Hardened KDBX database file parser
Documentation
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use crate::{
	config::{CompressionConfig, DatabaseConfig, InnerCipherConfig, KdfConfig, OuterCipherConfig},
	crypt::{Key256, calculate_sha256, sha256_key},
	db::{Database, DatabaseFormatError, DatabaseOpenError, GroupId, Value, fields},
	format::DatabaseVersion,
	key::{DatabaseKey, DatabaseKeyError},
};

use byteorder::{ByteOrder, LittleEndian};
use hybrid_array::Array as GenericArray;
use thiserror::Error;

use std::{collections::HashMap, convert::TryFrom};

#[derive(Debug)]
struct KDBHeader {
	// https://gist.github.com/lgg/e6ccc6e212d18dd2ecd8a8c116fb1e45
	pub flags: u32,
	pub subversion: u32,
	pub master_seed: Vec<u8>,   // 16 bytes
	pub encryption_iv: Vec<u8>, // 16 bytes
	pub num_groups: u32,
	pub num_entries: u32,
	pub contents_hash: Vec<u8>,  // 32 bytes
	pub transform_seed: Vec<u8>, // 32 bytes
	pub transform_rounds: u32,
}

const HEADER_SIZE: usize = 4 + 4 + 4 + 4 + 16 + 16 + 4 + 4 + 32 + 32 + 4; // first 4 bytes are the KeePass magic

impl TryFrom<&[u8]> for KDBHeader {
	type Error = DatabaseOpenError;

	#[allow(clippy::indexing_slicing)] // data length is checked
	fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
		if data.len() < HEADER_SIZE {
			return Err(DatabaseOpenError::UnexpectedEof);
		}

		Ok(KDBHeader {
			flags: LittleEndian::read_u32(&data[8..]),
			subversion: LittleEndian::read_u32(&data[12..]),
			master_seed: data[16..32].to_vec(),
			encryption_iv: data[32..48].to_vec(),
			num_groups: LittleEndian::read_u32(&data[48..]),
			num_entries: LittleEndian::read_u32(&data[52..]),
			contents_hash: data[56..88].to_vec(),
			transform_seed: data[88..120].to_vec(),
			transform_rounds: LittleEndian::read_u32(&data[120..]),
		})
	}
}

fn from_utf8(data: &[u8]) -> String {
	String::from_utf8_lossy(data).trim_end_matches('\0').to_owned()
}

fn expected_group_field_size(ftype: u16) -> Option<u32> {
	match ftype {
		0x0001 => Some(4), // GroupId
		0x0002 => None,    // GroupName (variable length)
		0x0003 => Some(5), // CreationTime
		0x0004 => Some(5), // LastModTime
		0x0005 => Some(5), // LastAccessTime
		0x0006 => Some(5), // ExpireTime
		0x0007 => Some(4), // ImageId
		0x0008 => Some(2), // Level
		0x0009 => Some(4), // Flags
		0xffff => Some(0), // End of group
		_ => None,         // Unknown field type
	}
}

fn parse_groups(db: &mut Database, header_num_groups: u32, data: &mut &[u8]) -> Result<HashMap<u32, GroupId>, DatabaseOpenError> {
	let mut gid_map: HashMap<u32, GroupId> = HashMap::new();
	gid_map.insert(0, db.root);

	// current branch of the group tree being parsed
	let mut branch: Vec<GroupId> = Vec::new();
	branch.push(db.root);

	// state variables for the current group being parsed
	let mut parsing_name: Option<String> = None;
	let mut parsing_level: Option<u16> = None;
	let mut parsing_gid: Option<u32> = None;

	// the total number of parsed groups
	let mut num_groups = 0;
	while num_groups < header_num_groups as usize {
		// Read group TLV
		let field_type = data.get(0..2).map(LittleEndian::read_u16).ok_or(DatabaseOpenError::UnexpectedEof)?;

		let field_size = data.get(2..6).map(LittleEndian::read_u32).ok_or(DatabaseOpenError::UnexpectedEof)?;

		let field_value = data.get(6..6 + field_size as usize).ok_or(DatabaseOpenError::UnexpectedEof)?;

		if let Some(expected_field_size) = expected_group_field_size(field_type)
			&& expected_field_size != field_size
		{
			return Err(DatabaseOpenError::Format(DatabaseFormatError::Kdb(KdbOpenError::InvalidFieldLength {
				field_type,
				field_size,
				expected_field_size,
			})));
		}

		match field_type {
			0x0000 => {} // KeePass ignores this field type

			// GroupId
			0x0001 => parsing_gid = Some(LittleEndian::read_u32(field_value)),

			// GroupName
			0x0002 => parsing_name = Some(from_utf8(field_value)),

			// Creation/LastMod/LastAccess/Expire times
			0x0003..=0x0006 => {}

			// ImageId
			0x0007 => {}

			// Level
			0x0008 => parsing_level = Some(LittleEndian::read_u16(field_value)),

			// Flags
			0x0009 => {}

			// End of group
			0xffff => {
				let group_id = parsing_gid.ok_or(DatabaseOpenError::Format(DatabaseFormatError::Kdb(KdbOpenError::InvalidGroupId(None))))?;

				let level = parsing_level.ok_or(DatabaseOpenError::Format(DatabaseFormatError::Kdb(KdbOpenError::InvalidGroupLevel {
					current: None,
					expected: branch.len() as u16,
				})))? as usize;

				let name = parsing_name.take().unwrap_or_default();

				let parent_id: GroupId = if level <= branch.len() {
					branch.truncate(level);
					*branch.last().unwrap_or(&db.root().id())
				} else {
					// Level is beyond the current depth, missing intermediate levels?
					return Err(DatabaseOpenError::Format(DatabaseFormatError::Kdb(KdbOpenError::InvalidGroupLevel {
						current: Some(level as u16),
						expected: branch.len() as u16,
					})));
				};

				#[allow(clippy::expect_used)] // parent_id is guaranteed to exist
				let mut parent = db.group_mut(parent_id).expect("parent group must exist");

				let mut group = parent.add_group();
				group.name = name;

				parsing_gid = None;
				parsing_level = None;

				gid_map.insert(group_id, group.id());

				branch.push(group.id());

				num_groups += 1;
			}
			_ => {
				return Err(DatabaseOpenError::Format(DatabaseFormatError::Kdb(KdbOpenError::InvalidGroupFieldType(field_type))));
			}
		}

		*data = data.get(6 + field_size as usize..).ok_or(DatabaseOpenError::UnexpectedEof)?;
	}

	if parsing_gid.is_some() {
		return Err(DatabaseOpenError::Format(DatabaseFormatError::Kdb(KdbOpenError::IncompleteGroup)));
	}

	Ok(gid_map)
}

fn expected_entry_field_size(ftype: u16) -> Option<u32> {
	match ftype {
		0x0000 => None,     // KeePass ignores this field type
		0x0001 => Some(16), // uuid
		0x0002 => Some(4),  // GroupId
		0x0003 => Some(4),  // ImageId
		0x0004 => None,     // Title (variable length)
		0x0005 => None,     // URL (variable length)
		0x0006 => None,     // UserName (variable length)
		0x0007 => None,     // Password (variable length)
		0x0008 => None,     // Additional (variable length)
		0x0009 => Some(5),  // CreationTime
		0x000a => Some(5),  // LastModTime
		0x000b => Some(5),  // LastAccessTime
		0x000c => Some(5),  // ExpireTime
		0x000d => None,     // BinaryDesc (variable length)
		0x000e => None,     // BinaryData (variable length)
		0xffff => Some(0),  // End of entry
		_ => None,          // Unknown field type
	}
}

fn parse_entries(db: &mut Database, gid_map: HashMap<u32, GroupId>, header_num_entries: u32, data: &mut &[u8]) -> Result<(), DatabaseOpenError> {
	let mut parsing_gid: Option<u32> = None;
	let mut parsing_fields: HashMap<String, Value<String>> = HashMap::new();

	let mut num_entries = 0;
	while num_entries < header_num_entries {
		let field_type = data.get(0..2).ok_or(DatabaseOpenError::UnexpectedEof)?;
		let field_type = LittleEndian::read_u16(field_type);

		let field_size = data.get(2..6).ok_or(DatabaseOpenError::UnexpectedEof)?;
		let field_size = LittleEndian::read_u32(field_size);

		let field_value = data.get(6..6 + field_size as usize).ok_or(DatabaseOpenError::UnexpectedEof)?;

		if let Some(expected_field_size) = expected_entry_field_size(field_type)
			&& expected_field_size != field_size
		{
			return Err(DatabaseOpenError::Format(DatabaseFormatError::Kdb(KdbOpenError::InvalidFieldLength {
				field_type,
				field_size,
				expected_field_size,
			})));
		}

		match field_type {
			// ignored by KeePass
			0x0000 => {} // KeePass ignores this field type

			// UUID
			0x0001 => {}

			// GroupId
			0x0002 => parsing_gid = Some(LittleEndian::read_u32(field_value)),

			// ImageId
			0x0003 => {}

			// Title
			0x0004 => {
				parsing_fields.insert(String::from(fields::TITLE), Value::unprotected(from_utf8(field_value)));
			}

			// URL
			0x0005 => {
				parsing_fields.insert(String::from(fields::URL), Value::unprotected(from_utf8(field_value)));
			}

			// UserName
			0x0006 => {
				parsing_fields.insert(String::from(fields::USERNAME), Value::unprotected(from_utf8(field_value)));
			}

			// Password
			0x0007 => {
				parsing_fields.insert(String::from(fields::PASSWORD), Value::protected(from_utf8(field_value)));
			}

			// Additional
			0x0008 => {
				parsing_fields.insert(String::from(fields::NOTES), Value::unprotected(from_utf8(field_value)));
			}

			// Creation/LastMod/LastAccess/Expire times
			0x0009..=0x000c => {}

			// BinaryDesc
			0x000d => {}

			// BinaryData
			0x000e => {}

			0xffff => {
				let gid = parsing_gid.ok_or(DatabaseOpenError::Format(DatabaseFormatError::Kdb(KdbOpenError::InvalidGroupId(None))))?;
				let group_id = *gid_map.get(&gid).ok_or(DatabaseOpenError::Format(DatabaseFormatError::Kdb(KdbOpenError::InvalidGroupId(Some(gid)))))?;

				#[allow(clippy::expect_used)] // group_id was checked before
				let mut group = db.group_mut(group_id).expect("group must exist");

				let mut entry = group.add_entry();
				entry.fields = std::mem::take(&mut parsing_fields);

				parsing_gid = None;
				num_entries += 1;
			}

			_ => {
				return Err(DatabaseOpenError::Format(DatabaseFormatError::Kdb(KdbOpenError::InvalidEntryFieldType(field_type))));
			}
		}

		*data = data.get(6 + field_size as usize..).ok_or(DatabaseOpenError::UnexpectedEof)?;
	}

	if parsing_gid.is_some() {
		return Err(DatabaseOpenError::Format(DatabaseFormatError::Kdb(KdbOpenError::IncompleteEntry)));
	}

	Ok(())
}

pub(crate) fn parse_kdb(data: &[u8], db_key: &DatabaseKey) -> Result<Database, DatabaseOpenError> {
	let header = KDBHeader::try_from(data)?;
	let version = DatabaseVersion::KDB(header.subversion as u16);

	// Rest of file after header is payload
	let payload_encrypted = data.get(HEADER_SIZE..).ok_or(DatabaseOpenError::UnexpectedEof)?;

	// derive master key from composite key, transform_seed, transform_rounds and master_seed
	let composite_key: Key256 = {
		let key_elements = db_key.get_key_elements()?;
		let key_elements: Vec<&[u8]> = key_elements.iter().map(|v| &v[..]).collect();
		if key_elements.len() == 1 {
			let mut k: Key256 = GenericArray::default().into();
			#[allow(clippy::indexing_slicing)] // key_elements is guaranteed to have 1 element
			k.as_mut_slice().copy_from_slice(key_elements[0]); // panics unless 32 bytes, as before
			k // single pass of SHA256, already done before the call to parse()
		} else {
			sha256_key(&key_elements) // second pass of SHA256
		}
	};
	// KDF is always AES
	let kdf_config = KdfConfig::Aes { rounds: u64::from(header.transform_rounds) };

	let transformed_key = kdf_config.get_kdf_seeded(&header.transform_seed).transform_key(&composite_key)?;

	let master_key = sha256_key(&[&header.master_seed, &transformed_key]);

	let outer_cipher_config = if header.flags & 2 != 0 {
		OuterCipherConfig::AES256
	} else if header.flags & 8 != 0 {
		OuterCipherConfig::Twofish
	} else {
		return Err(DatabaseOpenError::Format(DatabaseFormatError::Kdb(KdbOpenError::InvalidFixedCipherID(header.flags))));
	};

	// Decrypt payload (PKCS#7 padding is removed by the cipher)
	#[allow(clippy::expect_used)] // master key is fixed-length, should never fail
	let payload = outer_cipher_config
		.get_cipher(&master_key, header.encryption_iv.as_ref())
		.expect("Database key correctly derived")
		.decrypt(payload_encrypted)?;

	// Check if we decrypted correctly
	let hash = calculate_sha256(&[&payload]);
	if header.contents_hash != hash.as_slice() {
		return Err(DatabaseOpenError::Key(DatabaseKeyError::IncorrectKey));
	}

	let config = DatabaseConfig {
		version,
		outer_cipher_config,
		compression_config: CompressionConfig::None,
		inner_cipher_config: InnerCipherConfig::Plain,
		kdf_config,
		public_custom_data: Default::default(),
	};

	let mut db = Database::with_data(config, GroupId::new());
	db.root_mut().name = String::from("Root");
	let mut pos = payload.as_slice();
	let gid_map = parse_groups(&mut db, header.num_groups, &mut pos)?;
	parse_entries(&mut db, gid_map, header.num_entries, &mut pos)?;
	Ok(db)
}

/// Errors that can occur when opening a KeePass 1 database
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum KdbOpenError {
	/// A field has an invalid length (either too short or too long) compared to the expected
	/// length for its type
	#[error("Field of type {field_type} has invalid length {field_size}, expected {expected_field_size}")]
	InvalidFieldLength {
		/// The type of the field that has an invalid length
		field_type: u16,

		/// The actual length of the field as read from the database
		field_size: u32,

		/// The expected length of the field based on its type, if it is a known fixed-length type
		expected_field_size: u32,
	},

	/// A group has an invalid level that does not match the expected level based on the current
	/// depth of the group tree being parsed
	#[error("Invalid group level: got {current:?}, expected {expected}")]
	InvalidGroupLevel {
		/// The actual level of the group as read from the database, or `None` if the level field
		/// was missing
		current: Option<u16>,

		/// The expected level of the group based on the current depth of the group tree being
		/// parsed
		expected: u16,
	},

	/// Encountered the end of a group definition without finding a valid group ID field, or found
	/// a group ID that does not match any previously defined group
	#[error("Invalid group ID: {0:?}")]
	InvalidGroupId(Option<u32>),

	/// Encountered a field type in a group definition that is not recognized as a valid group
	/// field type
	#[error("Invalid group field type: {0}")]
	InvalidGroupFieldType(u16),

	/// Encountered the end of the file before the current group definition was properly terminated
	/// with an end-of-group field
	#[error("Group was not terminated before end of file")]
	IncompleteGroup,

	/// Encountered an entry definition that is missing a valid group ID field
	#[error("Entry is missing group ID")]
	EntryMissingGroupId,

	/// Encountered an invalid entry field type
	#[error("Invalid entry field type: {0}")]
	InvalidEntryFieldType(u16),

	/// Encountered the end of the file before the current entry definition was properly terminated
	#[error("Entry was not terminated before end of file")]
	IncompleteEntry,

	/// The database is encrypted with a cipher that is not recognized or supported
	#[error("Invalid fixed cipher ID: {0}")]
	InvalidFixedCipherID(u32),
}