keychain_parser 0.1.2

Parse the output of security(1) dump-keychain.
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
//! Parser for keychain access dumps.
use super::{error::LexError, Error, Result};
use logos::{Lexer, Logos};
use std::{borrow::Cow, collections::HashMap, ops::Range};

/// The value for the type of generic passwords
/// that are of the note type.
const NOTE_TYPE: &str = "note";

/// The key in the plist dictionary that contains the
/// value of a secure note.
const NOTE_PLIST_KEY: &str = "NOTE";

type LexResult<T> = std::result::Result<T, LexError>;

#[derive(Logos, Debug, PartialEq)]
enum OctalToken {
    #[regex("\\\\(\\d\\d\\d)")]
    OctalEscape,
}

/// Replace escaped octal sequences such as `\012` in a string.
pub fn unescape_octal(value: &str) -> Result<Cow<'_, str>> {
    let mut lex = OctalToken::lexer(value);
    let mut has_escape = false;
    let mut tokens = Vec::new();
    while let Some(token) = lex.next() {
        if let Ok(OctalToken::OctalEscape) = token {
            has_escape = true;
        }
        let span = lex.span();
        tokens.push((token, span));
    }

    if !has_escape {
        Ok(Cow::Borrowed(value))
    } else {
        let mut s = String::new();
        for (token, span) in tokens {
            if let Ok(OctalToken::OctalEscape) = token {
                let octal = &value[span.start + 1..span.end];
                let num = u32::from_str_radix(octal, 8)?;
                s.push(char::from_u32(num).ok_or_else(|| {
                    Error::InvalidOctalEscape(
                        value[span.start..span.end].to_owned(),
                    )
                })?);
            } else {
                s.push_str(&value[span]);
            }
        }
        Ok(Cow::Owned(s))
    }
}

/// Parse a plist and extract the value for a secure note.
pub fn plist_secure_note(
    value: &str,
    unescape: bool,
) -> Result<Option<Cow<str>>> {
    let plist = if unescape {
        unescape_octal(value)?
    } else {
        Cow::Borrowed(value)
    };
    let value: plist::Value = plist::from_bytes(plist.as_bytes())?;
    if let plist::Value::Dictionary(map) = value {
        if let Some(plist::Value::String(data)) = map.get(NOTE_PLIST_KEY) {
            return Ok(Some(Cow::Owned(data.to_owned())));
        }
    }
    Ok(None)
}

#[derive(Logos, Debug, PartialEq, Copy, Clone)]
#[logos(error = LexError)]
enum Token {
    #[token("keychain:")]
    Keychain,
    #[token("version:")]
    Version,
    #[token("class:")]
    Class,
    #[token("attributes:")]
    Attributes,
    #[token("data:")]
    Data,
    #[token("=")]
    Equality,
    #[token("\"")]
    DoubleQuote,
    #[regex("(?i:0x[a-f0-9]+)")]
    HexValue,
    #[regex("\\d+")]
    Number,
    #[token("<NULL>")]
    Null,
    #[regex("<(blob|timedate|uint32|sint32)>")]
    Type,
    #[regex(r"[ \t\r\n\f]+")]
    WhiteSpace,
}

/// Parse the dump for a keychain.
///
/// Octal sequences are not handled, you should call
/// `unescape_octal()` when you need to replace octal
/// escape sequences.
pub struct KeychainParser<'s> {
    source: &'s str,
}

impl<'s> KeychainParser<'s> {
    /// Create a new parser.
    pub fn new(source: &'s str) -> Self {
        Self { source }
    }

    /// Get a lex for the current source.
    fn lex(&self) -> Lexer<'s, Token> {
        Token::lexer(self.source)
    }

    /// Parse the keychain dump.
    pub fn parse(&self) -> Result<KeychainList<'s>> {
        let mut entries: Vec<KeychainEntry<'s>> = Vec::new();
        let mut lex = self.lex();
        let mut in_attributes = false;
        let mut next_token = lex.next();
        while let Some(token) = next_token {
            let token = token?;
            match token {
                Token::Keychain => {
                    in_attributes = false;
                    let advance_token = Self::consume_whitespace(&mut lex);

                    let range = Self::parse_quoted_string(
                        &mut lex,
                        self.source,
                        advance_token,
                    )?;

                    let entry = KeychainEntry {
                        keychain: &self.source[range],
                        version: None,
                        class: None,
                        data: None,
                        attributes: HashMap::new(),
                    };
                    entries.push(entry);
                }
                Token::Version => {
                    let token = Self::consume_whitespace(&mut lex);
                    let range =
                        Self::parse_number(&mut lex, self.source, token)?;
                    if let Some(last) = entries.last_mut() {
                        last.version = Some(&self.source[range]);
                    }
                }
                Token::Class => {
                    let token = Self::consume_whitespace(&mut lex);
                    let range = Self::parse_quoted_string(
                        &mut lex,
                        self.source,
                        token,
                    )?;
                    if let Some(last) = entries.last_mut() {
                        let class = &self.source[range];
                        last.class = Some(class.try_into()?);
                    }
                }
                Token::Attributes => {
                    in_attributes = true;
                    let token = Self::consume_whitespace(&mut lex);
                    next_token = token;
                    continue;
                }
                Token::Data => {
                    in_attributes = false;
                    let token = Self::consume_whitespace(&mut lex);

                    // It is allowed for data: to just be whitespace
                    // so we have to catch that here
                    if let Some(Ok(Token::Keychain)) = token {
                        next_token = token;
                        continue;
                    }

                    let value =
                        Self::parse_value(&mut lex, self.source, token)?;
                    if let Some(last) = entries.last_mut() {
                        last.data = Some(value);
                    }
                }
                _ => {
                    if in_attributes {
                        let range = Self::parse_attribute_name(
                            &mut lex,
                            self.source,
                            Some(Ok(token)),
                        )?;
                        let name = &self.source[range];
                        let name: AttributeName = name.try_into()?;

                        let token = Self::consume_whitespace(&mut lex);

                        let range = Self::parse_attribute_type(
                            &mut lex,
                            self.source,
                            token,
                        )?;
                        let attr_type = &self.source[range];
                        let attr_type: AttributeType =
                            attr_type.try_into()?;

                        // Consume the equals sign
                        let equals = lex.next();
                        if !matches!(equals, Some(Ok(Token::Equality))) {
                            return Err(Error::ParseExpectsEquals);
                        }

                        let value = Self::parse_attribute_value(
                            &mut lex,
                            self.source,
                            &attr_type,
                        )?;

                        if let Some(last) = entries.last_mut() {
                            let key = AttributeKey(name, attr_type);
                            last.attributes.insert(key, value);
                        }

                        let token = Self::consume_whitespace(&mut lex);
                        next_token = token;
                        continue;
                    }
                }
            }

            next_token = lex.next();
        }
        Ok(KeychainList { entries })
    }

    fn consume_whitespace(
        lex: &mut Lexer<Token>,
    ) -> Option<LexResult<Token>> {
        lex.by_ref().find(|t| !matches!(t, Ok(Token::WhiteSpace)))
    }

    fn parse_quoted_string(
        lex: &mut Lexer<Token>,
        source: &str,
        mut next_token: Option<LexResult<Token>>,
    ) -> Result<Range<usize>> {
        let mut in_quote = false;
        let mut begin: Range<usize> = lex.span();

        while let Some(token) = next_token {
            match token {
                Ok(Token::HexValue) => {
                    if !in_quote {
                        return Ok(lex.span());
                    }
                }
                Ok(Token::DoubleQuote) => {
                    if !in_quote {
                        begin = lex.span();
                        in_quote = true;
                    } else {
                        // We must check for EOF or newline to allow
                        // for nested quotes in the case of plist XML files
                        // used as values for secure notes
                        let finished = lex.remainder().is_empty()
                            || &lex.remainder()[0..1] == "\n";
                        if finished {
                            return Ok(begin.end..lex.span().start);
                        }
                    }
                }
                _ => {}
            }

            next_token = lex.next();
        }
        Err(Error::ParseNotQuoted(source[lex.span()].to_owned()))
    }

    fn parse_attribute_name(
        lex: &mut Lexer<Token>,
        source: &str,
        mut next_token: Option<LexResult<Token>>,
    ) -> Result<Range<usize>> {
        while let Some(token) = next_token {
            match token? {
                Token::HexValue => {
                    return Ok(lex.span());
                }
                Token::DoubleQuote => {
                    // We know that quoted attribute names are always
                    // 4 characters long so we do this parsing differently
                    // as the parse_quoted_string() function needs to check
                    // for a terminating newline in order to handle
                    // nested quotes properly, without this
                    // parse_quoted_string() would also need to test
                    // for a terminating '<' as the start of an attribute type
                    let start = lex.span().end;
                    let remainder = lex.remainder();
                    if remainder.len() >= 4 {
                        // Bump to ignore the 4 characters for the
                        // attribute name identifier
                        lex.bump(4);
                    }
                    let end_quote = lex.next();
                    if !matches!(end_quote, Some(Ok(Token::DoubleQuote))) {
                        return Err(Error::ParseAttributeNameQuote(
                            source[lex.span()].to_owned(),
                        ));
                    }
                    return Ok(start..lex.span().start);
                }
                _ => {}
            }
            next_token = lex.next();
        }
        Err(Error::ParseNotAttributeName(source[lex.span()].to_owned()))
    }

    fn parse_attribute_type(
        lex: &mut Lexer<Token>,
        source: &str,
        mut next_token: Option<LexResult<Token>>,
    ) -> Result<Range<usize>> {
        while let Some(token) = next_token {
            if let Token::Type = token? {
                return Ok(lex.span());
            }
            next_token = lex.next();
        }
        Err(Error::ParseNotAttributeType(source[lex.span()].to_owned()))
    }

    fn parse_attribute_value<'a>(
        lex: &mut Lexer<Token>,
        source: &'a str,
        _attr_type: &AttributeType,
    ) -> Result<Value<'a>> {
        let token = lex.next();
        Self::parse_value(lex, source, token)
    }

    fn parse_value<'a>(
        lex: &mut Lexer<Token>,
        source: &'a str,
        token: Option<LexResult<Token>>,
    ) -> Result<Value<'a>> {
        if let Some(token) = token {
            let token = token?;
            match token {
                Token::Null => return Ok(Value::Null),
                Token::HexValue => {
                    let hex = &source[lex.span()];
                    if lex.remainder().starts_with(r#"  ""#) {
                        let next_token = lex.next();
                        let range = Self::parse_quoted_string(
                            lex, source, next_token,
                        )?;
                        let value = &source[range];
                        return Ok(Value::BlobString(hex, value));
                    }
                    return Ok(Value::Blob(hex));
                }
                Token::DoubleQuote => {
                    let range = Self::parse_quoted_string(
                        lex,
                        source,
                        Some(Ok(token)),
                    )?;
                    let value = &source[range];
                    return Ok(Value::String(value));
                }
                _ => {
                    return Err(Error::ParseValue(
                        source[lex.span()].to_owned(),
                    ))
                }
            }
        }
        Err(Error::ParseValue(source[lex.span()].to_owned()))
    }

    fn parse_number(
        lex: &mut Lexer<Token>,
        source: &str,
        mut next_token: Option<LexResult<Token>>,
    ) -> Result<Range<usize>> {
        while let Some(token) = next_token {
            if let Token::Number = token? {
                return Ok(lex.span());
            }
            next_token = lex.next();
        }
        Err(Error::ParseNotNumber(source[lex.span()].to_owned()))
    }
}

/// Collection of keychain entries.
#[derive(Debug)]
pub struct KeychainList<'s> {
    entries: Vec<KeychainEntry<'s>>,
}

impl<'s> KeychainList<'s> {
    /// Get the collection of entries.
    pub fn entries(&self) -> &[KeychainEntry<'s>] {
        self.entries.as_slice()
    }

    /// Get the number of entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Determine if this list is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.len() == 0
    }

    /// Attempt to find a generic password entry.
    pub fn find_generic_password(
        &self,
        service: &str,
        account: &str,
    ) -> Option<&KeychainEntry<'_>> {
        self.entries.iter().find(|entry| {
            if let Some(EntryClass::GenericPassword) = entry.class {
                if let (Some((_, attr_service)), Some((_, attr_account))) = (
                    entry.find_attribute_by_name(
                        AttributeName::SecServiceItemAttr,
                    ),
                    entry.find_attribute_by_name(
                        AttributeName::SecAccountItemAttr,
                    ),
                ) {
                    if attr_service.matches(service)
                        && attr_account.matches(account)
                    {
                        return true;
                    }
                }
            }
            false
        })
    }

    /// Attempt to find a generic password note.
    pub fn find_generic_note(
        &self,
        service: &str,
    ) -> Option<&KeychainEntry<'_>> {
        self.entries.iter().find(|entry| {
            if let Some(EntryClass::GenericPassword) = entry.class {
                if let (Some((_, attr_service)), Some((_, attr_type))) = (
                    entry.find_attribute_by_name(
                        AttributeName::SecServiceItemAttr,
                    ),
                    entry.find_attribute_by_name(
                        AttributeName::SecTypeItemAttr,
                    ),
                ) {
                    if attr_service.matches(service)
                        && attr_type.matches(NOTE_TYPE)
                    {
                        return true;
                    }
                }
            }
            false
        })
    }
}

/// Entry in a keychain list.
#[derive(Debug)]
pub struct KeychainEntry<'s> {
    /// The keychain path.
    #[allow(dead_code)]
    keychain: &'s str,
    /// Keychain version.
    version: Option<&'s str>,
    /// Item class.
    class: Option<EntryClass>,
    /// Attributes mapping.
    attributes: HashMap<AttributeKey<'s>, Value<'s>>,
    /// Data for the entry.
    data: Option<Value<'s>>,
}

impl<'s> KeychainEntry<'s> {
    /// Get the data for this entry.
    pub fn data(&self) -> Option<&Value<'s>> {
        self.data.as_ref()
    }

    /// Attempt to find an attribute by name.
    pub fn find_attribute_by_name(
        &self,
        name: AttributeName<'_>,
    ) -> Option<(&AttributeType, &Value<'_>)> {
        self.attributes.iter().find_map(|(key, value)| {
            if key.0 == name {
                Some((&key.1, value))
            } else {
                None
            }
        })
    }

    /// Determine if this entry is a secure note.
    pub fn is_note(&self) -> bool {
        let type_attr =
            self.find_attribute_by_name(AttributeName::SecTypeItemAttr);
        if let Some((_, attr_type)) = type_attr {
            return attr_type.matches(NOTE_TYPE);
        }
        false
    }

    /// Attempt to get the entry data as a string
    /// for the generic password class.
    pub fn generic_data(&self) -> Result<Option<Cow<str>>> {
        if let Some(data) = &self.data {
            if let Some(EntryClass::GenericPassword) = self.class {
                if self.is_note() {
                    if let Value::BlobString(_, value) = data {
                        return plist_secure_note(value, true);
                    }
                } else {
                    match data {
                        Value::String(value) => {
                            return Ok(Some(Cow::Borrowed(value)))
                        }
                        Value::BlobString(_, value) => {
                            return Ok(Some(Cow::Borrowed(value)))
                        }
                        _ => {}
                    }
                }
            }
        }
        Ok(None)
    }
}

/// Represents the class of keychain entry.
#[derive(Debug)]
pub enum EntryClass {
    /// Generic password or note
    GenericPassword,
    /// Password stored by safari or other apps
    InternetPassword,
    /// Apple share password (deprecated)
    AppleSharePassword,
    /// Certificate
    Certificate,
    /// Public key
    PublicKey,
    /// Private key
    PrivateKey,
    /// Symmetric key
    SymmetricKey,
}

impl TryFrom<&str> for EntryClass {
    type Error = Error;

    fn try_from(value: &str) -> Result<Self> {
        match value {
            "genp" => Ok(Self::GenericPassword),
            "inet" => Ok(Self::InternetPassword),
            "ashp" => Ok(Self::AppleSharePassword),
            "0x80001000" => Ok(Self::Certificate),
            "0x0000000F" => Ok(Self::PublicKey),
            "0x00000010" => Ok(Self::PrivateKey),
            "0x00000011" => Ok(Self::SymmetricKey),
            _ => Err(Error::ParseUnknownClass(value.to_owned())),
        }
    }
}

/// The name of an attribute.
#[derive(Debug, Eq, PartialEq, Hash)]
pub enum AttributeName<'s> {
    // SEE: https://gist.github.com/santigz/601f4fd2f039d6ceb2198e2f9f4f01e0
    /// Hex value.
    Hex(&'s str),
    /// Creation date.
    SecCreationDateItemAttr,
    /// Modification date.
    SecModDateItemAttr,
    /// Description of the item.
    SecDescriptionItemAttr,
    /// Comment of the item.
    SecCommentItemAttr,
    /// Creator of the item.
    SecCreatorItemAttr,
    /// Type of the item.
    SecTypeItemAttr,
    /// Script code for the item.
    SecScriptCodeItemAttr,
    /// Label of the item.
    SecLabelItemAttr,
    /// Invisiblility.
    SecInvisibleItemAttr,
    /// Negative item.
    SecNegativeItemAttr,
    /// Custom icon.
    SecCustomIconItemAttr,
    /// Account name.
    SecAccountItemAttr,
    /// Service name.
    SecServiceItemAttr,
    /// Generic item.
    SecGenericItemAttr,
    /// Security domain.
    SecSecurityDomainItemAttr,
    /// Server item.
    SecServerItemAttr,
    /// Authentication type.
    SecAuthenticationTypeItemAttr,
    /// Port.
    SecPortItemAttr,
    /// Path.
    SecPathItemAttr,
    /// Volume.
    SecVolumeItemAttr,
    /// Address.
    SecAddressItemAttr,
    /// Signature.
    SecSignatureItemAttr,
    /// Protocol.
    SecProtocolItemAttr,
    /// Certificate.
    SecCertificateType,
    /// Certificate encoding.
    SecCertificateEncoding,
    /// Unknown.
    SecCrlType,
    /// Unknown.
    SecCrlEncoding,
    /// Unknown.
    SecAlias,
    /// Unknown attribute name.
    Unknown(&'s str),
}

impl<'s> TryFrom<&'s str> for AttributeName<'s> {
    type Error = Error;

    fn try_from(value: &'s str) -> Result<Self> {
        match value {
            "cdat" => Ok(Self::SecCreationDateItemAttr),
            "mdat" => Ok(Self::SecModDateItemAttr),
            "desc" => Ok(Self::SecDescriptionItemAttr),
            "icmt" => Ok(Self::SecCommentItemAttr),
            "crtr" => Ok(Self::SecCreatorItemAttr),
            "type" => Ok(Self::SecTypeItemAttr),
            "scrp" => Ok(Self::SecScriptCodeItemAttr),
            "labl" => Ok(Self::SecLabelItemAttr),
            "invi" => Ok(Self::SecInvisibleItemAttr),
            "nega" => Ok(Self::SecNegativeItemAttr),
            "cusi" => Ok(Self::SecCustomIconItemAttr),
            "acct" => Ok(Self::SecAccountItemAttr),
            "svce" => Ok(Self::SecServiceItemAttr),
            "gena" => Ok(Self::SecGenericItemAttr),
            "sdmn" => Ok(Self::SecSecurityDomainItemAttr),
            "srvr" => Ok(Self::SecServerItemAttr),
            "atyp" => Ok(Self::SecAuthenticationTypeItemAttr),
            "port" => Ok(Self::SecPortItemAttr),
            "path" => Ok(Self::SecPathItemAttr),
            "vlme" => Ok(Self::SecVolumeItemAttr),
            "addr" => Ok(Self::SecAddressItemAttr),
            "ssig" => Ok(Self::SecSignatureItemAttr),
            "ptcl" => Ok(Self::SecProtocolItemAttr),
            "ctyp" => Ok(Self::SecCertificateType),
            "cenc" => Ok(Self::SecCertificateEncoding),
            "crtp" => Ok(Self::SecCrlType),
            "crnc" => Ok(Self::SecCrlEncoding),
            "alis" => Ok(Self::SecAlias),
            // Unknown
            "prot" => Ok(Self::Unknown(value)),
            "hpky" => Ok(Self::Unknown(value)),
            "issu" => Ok(Self::Unknown(value)),
            "skid" => Ok(Self::Unknown(value)),
            "snbr" => Ok(Self::Unknown(value)),
            "subj" => Ok(Self::Unknown(value)),
            _ => {
                if value.starts_with("0x") {
                    Ok(Self::Hex(value))
                } else {
                    Err(Error::ParseUnknownAttributeName(value.to_string()))
                }
            }
        }
    }
}

/// Enumeration of attribute types.
#[derive(Debug, Eq, PartialEq, Hash)]
pub enum AttributeType {
    /// Blob attribute type.
    Blob,
    /// Uint32 attribute type.
    Uint32,
    /// Sint32 attribute type.
    Sint32,
    /// TimeDate attribute type.
    TimeDate,
}

impl TryFrom<&str> for AttributeType {
    type Error = Error;

    fn try_from(value: &str) -> Result<Self> {
        match value {
            "<blob>" => Ok(Self::Blob),
            "<uint32>" => Ok(Self::Uint32),
            "<sint32>" => Ok(Self::Sint32),
            "<timedate>" => Ok(Self::TimeDate),
            _ => Err(Error::ParseUnknownAttributeType(value.to_owned())),
        }
    }
}

/// Key for an attribute.
#[derive(Debug, Eq, PartialEq, Hash)]
pub struct AttributeKey<'s>(pub AttributeName<'s>, pub AttributeType);

/// Value of an attribute.
#[derive(Debug, Eq, PartialEq, Hash)]
pub enum Value<'s> {
    /// Null value.
    Null,
    /// Time date value.
    TimeDate(&'s str),
    /// Quoted string value.
    String(&'s str),
    /// Uint32 value.
    Uint32(&'s str),
    /// Sint32 value.
    Sint32(&'s str),
    /// Hexadecimal encoded bytes followed by a quoted string value.
    BlobString(&'s str, &'s str),
    /// Hexadecimal encoded bytes.
    Blob(&'s str),
}

impl<'s> Value<'s> {
    /// Get this value as a string.
    pub fn as_str(&self) -> &str {
        match *self {
            Self::Null => "",
            Self::TimeDate(value) => value,
            Self::String(value) => value,
            Self::Uint32(value) => value,
            Self::Sint32(value) => value,
            Self::BlobString(_, value) => value,
            Self::Blob(value) => value,
        }
    }

    /// Determine if this value matches the given input.
    ///
    /// For the `BlobString` variant this matches against the blob value and
    /// ignores the hex number.
    pub fn matches(&self, input: &str) -> bool {
        match *self {
            Self::Null => false,
            Self::TimeDate(value) => value == input,
            Self::String(value) => value == input,
            Self::Uint32(value) => value == input,
            Self::Sint32(value) => value == input,
            Self::BlobString(_, value) => value == input,
            Self::Blob(value) => value == input,
        }
    }
}