Skip to main content

keepass/format/
variant_dictionary.rs

1#[cfg(feature = "save_kdbx4")]
2use byteorder::WriteBytesExt;
3use byteorder::{ByteOrder, LittleEndian};
4#[cfg(feature = "save_kdbx4")]
5use std::io::Write;
6use std::{
7    collections::HashMap,
8    ops::{Deref, DerefMut},
9};
10use thiserror::Error;
11
12#[cfg(feature = "save_kdbx4")]
13use crate::format::io::WriteLengthTaggedExt;
14
15pub const VARIANT_DICTIONARY_VERSION: u16 = 0x100;
16pub const VARIANT_DICTIONARY_END: u8 = 0x0;
17
18pub const U32_TYPE_ID: u8 = 0x04;
19pub const U64_TYPE_ID: u8 = 0x05;
20pub const BOOL_TYPE_ID: u8 = 0x08;
21pub const I32_TYPE_ID: u8 = 0x0c;
22pub const I64_TYPE_ID: u8 = 0x0d;
23pub const STR_TYPE_ID: u8 = 0x18;
24pub const BYTES_TYPE_ID: u8 = 0x42;
25
26/// A dictionary of key-value pairs, with typed values
27#[derive(Debug, PartialEq, Eq, Clone, Default)]
28#[cfg_attr(feature = "serialization", derive(serde::Serialize))]
29pub struct VariantDictionary(HashMap<String, VariantDictionaryValue>);
30
31impl Deref for VariantDictionary {
32    type Target = HashMap<String, VariantDictionaryValue>;
33
34    fn deref(&self) -> &Self::Target {
35        &self.0
36    }
37}
38
39impl DerefMut for VariantDictionary {
40    fn deref_mut(&mut self) -> &mut Self::Target {
41        &mut self.0
42    }
43}
44
45impl VariantDictionary {
46    /// Create a new, empty VariantDictionary
47    pub fn new() -> Self {
48        Self(HashMap::new())
49    }
50
51    pub(crate) fn parse(buffer: &[u8]) -> Result<VariantDictionary, VariantDictionaryError> {
52        let version = buffer.get(0..2).ok_or(VariantDictionaryError::UnexpectedEof)?;
53        let version = LittleEndian::read_u16(version);
54
55        if version != VARIANT_DICTIONARY_VERSION {
56            return Err(VariantDictionaryError::InvalidVersion { version });
57        }
58
59        let mut pos = 2;
60        let mut data = HashMap::new();
61
62        while pos + 9 < buffer.len() {
63            let value_type = *buffer.get(pos).ok_or(VariantDictionaryError::UnexpectedEof)?;
64            pos += 1;
65
66            let key_length = buffer
67                .get(pos..(pos + 4))
68                .ok_or(VariantDictionaryError::UnexpectedEof)?;
69            let key_length = LittleEndian::read_u32(key_length) as usize;
70            pos += 4;
71
72            let key = buffer
73                .get(pos..(pos + key_length))
74                .ok_or(VariantDictionaryError::UnexpectedEof)?;
75            let key = String::from_utf8_lossy(key).to_string();
76            pos += key_length;
77
78            let value_length = buffer
79                .get(pos..(pos + 4))
80                .ok_or(VariantDictionaryError::UnexpectedEof)?;
81            let value_length = LittleEndian::read_u32(value_length) as usize;
82            pos += 4;
83
84            let value_buffer = buffer
85                .get(pos..(pos + value_length))
86                .ok_or(VariantDictionaryError::UnexpectedEof)?;
87            pos += value_length;
88
89            let value = match value_type {
90                U32_TYPE_ID => VariantDictionaryValue::UInt32(LittleEndian::read_u32(value_buffer)),
91                U64_TYPE_ID => VariantDictionaryValue::UInt64(LittleEndian::read_u64(value_buffer)),
92                BOOL_TYPE_ID => VariantDictionaryValue::Bool(value_buffer != [0]),
93                I32_TYPE_ID => VariantDictionaryValue::Int32(LittleEndian::read_i32(value_buffer)),
94                I64_TYPE_ID => VariantDictionaryValue::Int64(LittleEndian::read_i64(value_buffer)),
95                STR_TYPE_ID => {
96                    VariantDictionaryValue::String(String::from_utf8_lossy(value_buffer).to_string())
97                }
98                BYTES_TYPE_ID => VariantDictionaryValue::ByteArray(value_buffer.to_vec()),
99                _ => {
100                    return Err(VariantDictionaryError::InvalidValueType { value_type });
101                }
102            };
103
104            data.insert(key, value);
105        }
106
107        if pos == buffer.len()
108            || *buffer.get(pos).ok_or(VariantDictionaryError::UnexpectedEof)? != VARIANT_DICTIONARY_END
109        {
110            // even though we can determine when to stop parsing a VariantDictionary by where we
111            // are in the buffer, there should always be a value_type = 0 entry to denote that a
112            // VariantDictionary is finished
113            return Err(VariantDictionaryError::NotTerminated);
114        }
115
116        Ok(VariantDictionary(data))
117    }
118
119    #[cfg(feature = "save_kdbx4")]
120    pub(crate) fn dump(&self, writer: &mut dyn Write) -> Result<(), std::io::Error> {
121        writer.write_u16::<LittleEndian>(VARIANT_DICTIONARY_VERSION)?;
122
123        for (field_name, field_value) in &self.0 {
124            match field_value {
125                VariantDictionaryValue::UInt32(value) => {
126                    writer.write_u8(U32_TYPE_ID)?;
127                    writer.write_with_len(field_name.as_bytes())?;
128                    writer.write_u32::<LittleEndian>(4)?;
129                    writer.write_u32::<LittleEndian>(*value)?;
130                }
131                VariantDictionaryValue::UInt64(value) => {
132                    writer.write_u8(U64_TYPE_ID)?;
133                    writer.write_with_len(field_name.as_bytes())?;
134                    writer.write_u32::<LittleEndian>(8)?;
135                    writer.write_u64::<LittleEndian>(*value)?;
136                }
137                VariantDictionaryValue::Bool(value) => {
138                    writer.write_u8(BOOL_TYPE_ID)?;
139                    writer.write_with_len(field_name.as_bytes())?;
140                    writer.write_u32::<LittleEndian>(1)?;
141                    writer.write_u8(if *value { 1 } else { 0 })?;
142                }
143                VariantDictionaryValue::Int32(value) => {
144                    writer.write_u8(I32_TYPE_ID)?;
145                    writer.write_with_len(field_name.as_bytes())?;
146                    writer.write_u32::<LittleEndian>(4)?;
147                    writer.write_i32::<LittleEndian>(*value)?;
148                }
149                VariantDictionaryValue::Int64(value) => {
150                    writer.write_u8(I64_TYPE_ID)?;
151                    writer.write_with_len(field_name.as_bytes())?;
152                    writer.write_u32::<LittleEndian>(8)?;
153                    writer.write_i64::<LittleEndian>(*value)?;
154                }
155                VariantDictionaryValue::String(value) => {
156                    writer.write_u8(STR_TYPE_ID)?;
157                    writer.write_with_len(field_name.as_bytes())?;
158                    writer.write_with_len(value.as_bytes())?;
159                }
160                VariantDictionaryValue::ByteArray(value) => {
161                    writer.write_u8(BYTES_TYPE_ID)?;
162                    writer.write_with_len(field_name.as_bytes())?;
163                    writer.write_with_len(value)?;
164                }
165            };
166        }
167
168        // signify end of variant dictionary
169        writer.write_u8(VARIANT_DICTIONARY_END)?;
170        Ok(())
171    }
172
173    /// Get a value from the VariantDictionary, returning an error if the key is missing or the
174    /// value is of the wrong type
175    pub fn get_typed<'a, T: 'a>(&'a self, key: &str) -> Result<&'a T, VariantDictionaryError>
176    where
177        &'a VariantDictionaryValue: Into<Option<&'a T>>,
178    {
179        let vdv = self
180            .0
181            .get(key)
182            .ok_or_else(|| VariantDictionaryError::MissingKey { key: key.to_owned() })?;
183
184        vdv.into()
185            .ok_or_else(|| VariantDictionaryError::Mistyped { key: key.to_owned() })
186    }
187
188    /// Set a value in the VariantDictionary
189    pub fn set<T>(&mut self, key: &str, value: T)
190    where
191        T: Into<VariantDictionaryValue>,
192    {
193        self.insert(key.to_string(), value.into());
194    }
195}
196
197/// A value in a VariantDictionary, which can be one of several types
198#[derive(Debug, PartialEq, Eq, Clone)]
199#[cfg_attr(feature = "serialization", derive(serde::Serialize))]
200#[non_exhaustive]
201pub enum VariantDictionaryValue {
202    /// An unsigned 32-bit integer value
203    UInt32(u32),
204
205    /// An unsigned 64-bit integer value
206    UInt64(u64),
207
208    /// A boolean value
209    Bool(bool),
210
211    /// A signed 32-bit integer value
212    Int32(i32),
213
214    /// A signed 64-bit integer value
215    Int64(i64),
216
217    /// A UTF-8 encoded string value
218    String(String),
219
220    /// A byte array value
221    ByteArray(Vec<u8>),
222}
223
224impl From<u32> for VariantDictionaryValue {
225    fn from(v: u32) -> Self {
226        VariantDictionaryValue::UInt32(v)
227    }
228}
229
230impl From<u64> for VariantDictionaryValue {
231    fn from(v: u64) -> Self {
232        VariantDictionaryValue::UInt64(v)
233    }
234}
235
236impl From<i32> for VariantDictionaryValue {
237    fn from(v: i32) -> Self {
238        VariantDictionaryValue::Int32(v)
239    }
240}
241
242impl From<i64> for VariantDictionaryValue {
243    fn from(v: i64) -> Self {
244        VariantDictionaryValue::Int64(v)
245    }
246}
247
248impl From<bool> for VariantDictionaryValue {
249    fn from(v: bool) -> Self {
250        VariantDictionaryValue::Bool(v)
251    }
252}
253
254impl From<String> for VariantDictionaryValue {
255    fn from(v: String) -> Self {
256        VariantDictionaryValue::String(v)
257    }
258}
259
260impl From<Vec<u8>> for VariantDictionaryValue {
261    fn from(v: Vec<u8>) -> Self {
262        VariantDictionaryValue::ByteArray(v)
263    }
264}
265
266impl<'a> From<&'a VariantDictionaryValue> for Option<&'a u32> {
267    fn from(val: &'a VariantDictionaryValue) -> Self {
268        match val {
269            VariantDictionaryValue::UInt32(v) => Some(v),
270            _ => None,
271        }
272    }
273}
274
275impl<'a> From<&'a VariantDictionaryValue> for Option<&'a u64> {
276    fn from(val: &'a VariantDictionaryValue) -> Self {
277        match val {
278            VariantDictionaryValue::UInt64(v) => Some(v),
279            _ => None,
280        }
281    }
282}
283
284impl<'a> From<&'a VariantDictionaryValue> for Option<&'a bool> {
285    fn from(val: &'a VariantDictionaryValue) -> Self {
286        match val {
287            VariantDictionaryValue::Bool(v) => Some(v),
288            _ => None,
289        }
290    }
291}
292
293impl<'a> From<&'a VariantDictionaryValue> for Option<&'a i32> {
294    fn from(val: &'a VariantDictionaryValue) -> Self {
295        match val {
296            VariantDictionaryValue::Int32(v) => Some(v),
297            _ => None,
298        }
299    }
300}
301
302impl<'a> From<&'a VariantDictionaryValue> for Option<&'a i64> {
303    fn from(val: &'a VariantDictionaryValue) -> Self {
304        match val {
305            VariantDictionaryValue::Int64(v) => Some(v),
306            _ => None,
307        }
308    }
309}
310
311impl<'a> From<&'a VariantDictionaryValue> for Option<&'a String> {
312    fn from(val: &'a VariantDictionaryValue) -> Self {
313        match val {
314            VariantDictionaryValue::String(v) => Some(v),
315            _ => None,
316        }
317    }
318}
319
320impl<'a> From<&'a VariantDictionaryValue> for Option<&'a Vec<u8>> {
321    fn from(val: &'a VariantDictionaryValue) -> Self {
322        match val {
323            VariantDictionaryValue::ByteArray(v) => Some(v),
324            _ => None,
325        }
326    }
327}
328
329/// Errors while parsing a VariantDictionary
330#[derive(Debug, Error)]
331#[non_exhaustive]
332pub enum VariantDictionaryError {
333    /// An invalid VariantDictionary version was encountered.
334    #[error("Invalid variant dictionary version: {}", version)]
335    InvalidVersion {
336        /// The version number that was encountered
337        version: u16,
338    },
339
340    /// An invalid value type was encountered while parsing a VariantDictionary.
341    #[error("Invalid value type: {}", value_type)]
342    InvalidValueType {
343        /// The value type identifier that was encountered
344        value_type: u8,
345    },
346
347    /// A required key was missing from the VariantDictionary.
348    #[error("Missing key: {}", key)]
349    MissingKey {
350        /// The name of the missing key
351        key: String,
352    },
353
354    /// A value was found for the specified key, but it was of an unexpected type.
355    #[error("Mistyped value: {}", key)]
356    Mistyped {
357        /// The name of the key whose value was mistyped
358        key: String,
359    },
360
361    /// The VariantDictionary did not end with a null byte (0x00) as expected.
362    #[error("VariantDictionary did not end with null byte, when it should")]
363    NotTerminated,
364
365    /// An unexpected end of file was encountered while parsing the VariantDictionary
366    #[error("Unexpected end of file while parsing VariantDictionary")]
367    UnexpectedEof,
368}
369
370#[allow(clippy::unwrap_used)]
371#[cfg(test)]
372mod variant_dictionary_tests {
373    use hex_literal::hex;
374
375    use super::*;
376
377    #[test]
378    fn parsing_errors() -> Result<(), VariantDictionaryError> {
379        let res = VariantDictionary::parse("not-a-variant-dictionary".as_bytes());
380        assert!(matches!(res, Err(VariantDictionaryError::InvalidVersion { .. })));
381
382        let res = VariantDictionary::parse(&hex!("0001"));
383        assert!(matches!(res, Err(VariantDictionaryError::NotTerminated)));
384
385        let res = VariantDictionary::parse(&hex!("000100"));
386        assert!(res.is_ok());
387
388        //                                        ver t key_len key   val_len value   termination
389        //                                        |   | |       |     |       |       |
390        let res = VariantDictionary::parse(&hex!("000104030000004142430400000015CD5B0700"))?;
391        assert_eq!(res.get_typed::<u32>("ABC")?, &123456789);
392
393        //                                        ver t key_len key val_len termination
394        //                                        |   | |       |   |       |
395        let res = VariantDictionary::parse(&hex!("0001AA0200000041420000000000"));
396        dbg!(&res);
397        assert!(matches!(
398            res,
399            Err(VariantDictionaryError::InvalidValueType { value_type: 0xAA })
400        ));
401
402        Ok(())
403    }
404
405    #[test]
406    #[cfg(feature = "save_kdbx4")]
407    fn variant_dictionary() {
408        let mut vd = VariantDictionary::new();
409
410        vd.set("a-u32", 42u32);
411        vd.set("a-u64", 1337u64);
412        vd.set("a-i32", -2i32);
413        vd.set("a-i64", -31337i64);
414        vd.set("a-bool", true);
415        vd.set("a-string", "Testing".to_string());
416        vd.set("a-bytes", "testing".as_bytes().to_vec());
417
418        assert!(vd.get_typed::<bool>("key-not-exist").is_err());
419
420        assert!(vd.get_typed::<u32>("a-string").is_err());
421        assert!(vd.get_typed::<u64>("a-string").is_err());
422        assert!(vd.get_typed::<i32>("a-string").is_err());
423        assert!(vd.get_typed::<i64>("a-string").is_err());
424        assert!(vd.get_typed::<bool>("a-string").is_err());
425        assert!(vd.get_typed::<String>("a-bytes").is_err());
426        assert!(vd.get_typed::<Vec<u8>>("a-string").is_err());
427
428        assert_eq!(vd.get_typed::<u32>("a-u32").unwrap(), &42u32);
429        assert_eq!(vd.get_typed::<u64>("a-u64").unwrap(), &1337u64);
430        assert_eq!(vd.get_typed::<i32>("a-i32").unwrap(), &-2i32);
431        assert_eq!(vd.get_typed::<i64>("a-i64").unwrap(), &-31337i64);
432        assert_eq!(vd.get_typed::<bool>("a-bool").unwrap(), &true);
433        assert_eq!(vd.get_typed::<String>("a-string").unwrap(), "Testing");
434        assert_eq!(vd.get_typed::<Vec<u8>>("a-bytes").unwrap(), "testing".as_bytes());
435
436        let mut vd_data = Vec::new();
437        vd.dump(&mut vd_data).unwrap();
438
439        let vd_parsed = VariantDictionary::parse(&vd_data).unwrap();
440        assert_eq!(vd_parsed, vd);
441    }
442}