iso7816-tlv 0.4.1

tools and utilities for handling TLV data as defined in ISO/IEC 7816-4
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
use alloc::vec::Vec;
use core::fmt;

use untrusted::{Input, Reader};

use super::{Tag, Value};
use crate::{Result, TlvError};

/// BER-TLV structure, following ISO/IEC 7816-4.
/// > # BER-TLV data objects
/// > Each BER-TLV data object consists of two or three consecutive fields
/// > (see the basic encoding rules of ASN.1 in ISO/IEC 8825-1):
/// > a mandatory tag field, a mandatory length field and a conditional value field.
/// > - The tag field consists of one or more consecutive bytes.
/// >   It indicates a class and an encoding and it encodes a tag number.
/// >   The value '00' is invalid for the first byte of tag fields (see ISO/IEC 8825-1).
/// > - The length field consists of one or more consecutive bytes.
/// >   It encodes a length, i.e., a number denoted N.
/// > - If N is zero, there is no value field, i.e., the data object is empty.
/// >   Otherwise (N > 0), the value field consists of N consecutive bytes.
#[derive(PartialEq, Debug, Clone)]
pub struct Tlv {
  tag: Tag,
  value: Value,
}

impl Tlv {
  /// Create a BER-TLV data object from valid tag and value.alloc
  /// # Errors
  /// Fails with `TlvError::Inconsistant`
  /// if the tag indicates a contructed value (resp. primitive) and the
  /// value is primitive (resp. contructed).
  pub fn new(tag: Tag, value: Value) -> Result<Self> {
    match value {
      Value::Constructed(_) => {
        if !tag.is_constructed() {
          return Err(TlvError::Inconsistant);
        }
      }
      _ => {
        if tag.is_constructed() {
          return Err(TlvError::Inconsistant);
        }
      }
    }
    Ok(Self { tag, value })
  }

  /// Get BER-TLV  tag.
  #[must_use]
  pub fn tag(&self) -> &Tag {
    &self.tag
  }

  /// Get BER-TLV value length
  #[must_use]
  pub fn length(&self) -> usize {
    self.len()
  }

  /// Get BER-TLV value
  #[must_use]
  pub fn value(&self) -> &Value {
    &self.value
  }

  fn len_length(l: usize) -> usize {
    match l {
      0..=127 => 1,
      128..=255 => 2,
      256..=65_535 => 3,
      65_536..=16_777_215 => 4,
      _ => 5,
    }
  }

  #[allow(clippy::cast_possible_truncation)]
  fn inner_len_to_vec(&self) -> Vec<u8> {
    let l = self.value.len_as_bytes();
    if l < 0x7f {
      vec![l as u8]
    } else {
      let mut ret: Vec<u8> = l
        .to_be_bytes()
        .iter()
        .skip_while(|&x| *x == 0)
        .cloned()
        .collect();
      ret.insert(0, 0x80 | ret.len() as u8);
      ret
    }
  }

  pub(crate) fn len(&self) -> usize {
    let inner_len = self.value.len_as_bytes();
    self.tag.len_as_bytes() + Self::len_length(inner_len) + inner_len
  }

  /// serializes self into a byte vector.
  #[must_use]
  pub fn to_vec(&self) -> Vec<u8> {
    let mut ret: Vec<u8> = Vec::new();
    ret.extend(self.tag.to_bytes().iter());
    ret.append(&mut self.inner_len_to_vec());
    match &self.value {
      Value::Primitive(v) => ret.extend(v.iter()),
      Value::Constructed(tlv) => {
        for t in tlv {
          ret.append(&mut t.to_vec());
        }
      }
    };
    ret
  }

  fn read_len(r: &mut Reader) -> Result<usize> {
    let mut ret: usize = 0;
    let x = r.read_byte()?;
    if x & 0x80 == 0 {
      ret = x as usize;
    } else {
      let n_bytes = x as usize & 0x7f;
      if n_bytes > 4 {
        return Err(TlvError::InvalidLength);
      }
      for _ in 0..n_bytes {
        let x = r.read_byte()?;
        ret = ret << 8 | x as usize;
      }
    }
    Ok(ret)
  }

  fn read(r: &mut Reader) -> Result<Self> {
    let tag = Tag::read(r)?;
    let len = Self::read_len(r)?;

    let ret = if tag.is_constructed() {
      let mut val = Value::Constructed(vec![]);
      while val.len_as_bytes() < len {
        let tlv = Self::read(r)?;
        val.push(tlv)?;
      }
      Self::new(tag, val)?
    } else {
      let content = r.read_bytes(len)?;
      Self::new(tag, Value::Primitive(content.as_slice_less_safe().to_vec()))?
    };
    if ret.value.len_as_bytes() == len {
      Ok(ret)
    } else {
      Err(TlvError::Inconsistant)
    }
  }

  /// Parses a byte array into a BER-TLV structure.
  /// This also returns the unprocessed data.
  pub fn parse(input: &[u8]) -> (Result<Self>, &[u8]) {
    let mut r = Reader::new(Input::from(input));
    (
      Self::read(&mut r),
      r.read_bytes_to_end().as_slice_less_safe(),
    )
  }

  /// Parses a byte array into a BER-TLV structure.
  /// Input must exactly match a BER-TLV object.
  /// # Errors
  /// Fails with `TlvError::InvalidInput` if input does not match a BER-TLV object.
  pub fn from_bytes(input: &[u8]) -> Result<Self> {
    let (r, n) = Self::parse(input);
    if n.is_empty() {
      r
    } else {
      Err(TlvError::InvalidInput)
    }
  }

  /// Finds first occurence of a TLV object with given tag in self.
  #[must_use]
  pub fn find(&self, tag: &Tag) -> Option<&Self> {
    match &self.value {
      Value::Primitive(_) => {
        if self.tag == *tag {
          Some(&self)
        } else {
          None
        }
      }
      Value::Constructed(e) => {
        for x in e {
          match x.find(tag) {
            None => (),
            Some(e) => return Some(e),
          }
        }
        None
      }
    }
  }

  /// find all occurences of TLV objects with given given tag in self.
  /// Note that searching `ContextSpecific` class tag (0x80 for instance) will return
  /// a vector of possibly unrelated tlv data.
  #[must_use]
  pub fn find_all(&self, tag: &Tag) -> Vec<&Self> {
    let mut ret: Vec<&Self> = Vec::new();
    match &self.value {
      Value::Primitive(_) => {
        if self.tag == *tag {
          ret.push(self);
        }
      }
      Value::Constructed(e) => {
        for x in e {
          let v = x.find(tag);
          ret.extend(v);
        }
      }
    }
    ret
  }
}

impl fmt::Display for Tlv {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "{}, ", self.tag)?;
    write!(f, "len={}, ", self.value.len_as_bytes())?;
    write!(f, "value:")?;

    match &self.value {
      Value::Primitive(e) => {
        for x in e {
          write!(f, "{:02X}", x)?
        }
      }
      Value::Constructed(e) => {
        let padding_len = if let Some(width) = f.width() {
          width + 4
        } else {
          4
        };
        for x in e {
          writeln!(f)?;
          write!(
            f,
            "{}{:>padding$}",
            " ".repeat(padding_len),
            x,
            padding = padding_len
          )?;
        }
      }
    };
    Ok(())
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use core::convert::TryFrom;

  #[test]
  fn tlv_to_from_vec_primitive() -> Result<()> {
    let tlv = Tlv::new(Tag::try_from(1_u32)?, Value::Primitive(vec![0]))?;
    assert_eq!(vec![1, 1, 0], tlv.to_vec());
    {
      let data = vec![0_u8; 255];
      let tlv = Tlv::new(Tag::try_from(1_u32)?, Value::Primitive(data.clone()))?;
      let mut expected = vec![1_u8, 0x81, 0xFF];
      expected.append(&mut data.clone());
      assert_eq!(expected, tlv.to_vec());
      assert_eq!(Tag::try_from(1_u32)?, *tlv.tag());
      assert_eq!(Value::Primitive(data), *tlv.value());

      let mut r = Reader::new(Input::from(&expected));
      let read = Tlv::read(&mut r)?;
      assert_eq!(tlv, read);
    }
    {
      let data = vec![0_u8; 256];
      let tlv = Tlv::new(Tag::try_from(1_u32)?, Value::Primitive(data.clone()))?;
      let mut expected = vec![1_u8, 0x82, 0x01, 0x00];
      expected.append(&mut data.clone());
      assert_eq!(expected, tlv.to_vec());
      assert_eq!(Tag::try_from(1_u32)?, *tlv.tag());
      assert_eq!(Value::Primitive(data), *tlv.value());

      let mut r = Reader::new(Input::from(&expected));
      let read = Tlv::read(&mut r)?;
      assert_eq!(tlv, read);
    }
    {
      let data = vec![0_u8; 65_536];
      let tlv = Tlv::new(Tag::try_from(1_u32)?, Value::Primitive(data.clone()))?;
      let mut expected = vec![1_u8, 0x83, 0x01, 0x00, 0x00];
      expected.append(&mut data.clone());
      assert_eq!(expected, tlv.to_vec());
      assert_eq!(Tag::try_from(1_u32)?, *tlv.tag());
      assert_eq!(Value::Primitive(data), *tlv.value());

      let mut r = Reader::new(Input::from(&expected));
      let read = Tlv::read(&mut r)?;
      assert_eq!(tlv, read);
    }

    Ok(())
  }

  #[test]
  #[allow(clippy::cast_possible_truncation)]
  fn tlv_to_from_vec_constructed() -> Result<()> {
    let base = Tlv::new(Tag::try_from(1_u32)?, Value::Primitive(vec![0]))?;
    let mut construct = Value::Constructed(vec![base.clone(), base.clone(), base.clone()]);

    let tlv = Tlv::new(Tag::try_from("7f22")?, construct.clone())?;
    let mut expected = vec![0x7f_u8, 0x22, 9];
    expected.append(&mut base.to_vec());
    expected.append(&mut base.to_vec());
    expected.append(&mut base.to_vec());
    assert_eq!(expected, tlv.to_vec());

    assert_eq!(Tag::try_from("7f22")?, *tlv.tag());
    assert_eq!(construct, *tlv.value());

    let mut r = Reader::new(Input::from(&expected));
    let read = Tlv::read(&mut r)?;
    assert_eq!(tlv, read);

    construct.push(base.clone())?;
    expected[2] += base.len() as u8;
    expected.append(&mut base.to_vec());
    let tlv = Tlv::new(Tag::try_from("7f22")?, construct)?;
    assert_eq!(expected, tlv.to_vec());

    let mut r = Reader::new(Input::from(&expected));
    let read = Tlv::read(&mut r)?;
    assert_eq!(tlv, read);

    Ok(())
  }

  #[test]
  fn parse() -> Result<()> {
    let primitive_bytes = vec![1, 1, 0];
    let more_bytes = vec![1_u8; 10];
    let mut input = vec![0x7f_u8, 0x22, 9];
    input.extend(&primitive_bytes);
    input.extend(&primitive_bytes);
    input.extend(&primitive_bytes);
    let expected = input.clone();
    input.extend(&more_bytes);
    let (tlv, left) = Tlv::parse(&input);
    assert_eq!(expected, tlv?.to_vec());
    assert_eq!(more_bytes, left);
    Ok(())
  }

  #[cfg(feature = "std")]
  #[test]
  #[allow(clippy::redundant_clone)] // keep redundant_clone to have fewer modification if test is expanded
  fn display() -> Result<()> {
    let base = Tlv::new(Tag::try_from(0x80_u32)?, Value::Primitive(vec![0]))?;
    let construct = Value::Constructed(vec![base.clone(), base.clone()]);
    let tlv = Tlv::new(Tag::try_from("7f22")?, construct.clone())?;

    let mut construct2 = construct.clone();
    construct2.push(tlv)?;
    construct2.push(base)?;
    let t = Tag::try_from("3F32")?;
    let tlv = Tlv::new(t, construct2)?;
    println!("{}", tlv);
    Ok(())
  }

  #[test]
  #[allow(clippy::redundant_clone)] // keep redundant_clone to have fewer modification if test is expanded
  fn find() -> Result<()> {
    let base = Tlv::new(Tag::try_from(0x80_u32)?, Value::Primitive(vec![0]))?;
    let t = base.clone();

    // shall return self
    assert_eq!(Some(&t), t.find(&Tag::try_from(0x80_u32)?));
    assert!(t.find(&Tag::try_from(0x81_u32)?).is_none());

    let construct = Value::Constructed(vec![t, base.clone()]);
    let tlv = Tlv::new(Tag::try_from("7f22")?, construct.clone())?;
    assert_eq!(None, tlv.find(&Tag::try_from(0x81_u32)?));
    if let Some(found) = tlv.find(&Tag::try_from(0x80_u32)?) {
      assert_eq!(base.clone(), *found);
    } else {
      panic!("Tlv not found");
    }
    Ok(())
  }

  #[test]
  #[allow(clippy::redundant_clone)] // keep redundant_clone to have fewer modification if test is expanded
  fn find_all() -> Result<()> {
    let base = Tlv::new(Tag::try_from(0x80_u32)?, Value::Primitive(vec![0]))?;
    let t = base.clone();

    // shall return self
    assert_eq!(1, t.find_all(&Tag::try_from(0x80_u32)?).len());
    assert_eq!(0, t.find_all(&Tag::try_from(0x81_u32)?).len());

    let construct = Value::Constructed(vec![t, base.clone()]);
    let tlv = Tlv::new(Tag::try_from("7f22")?, construct.clone())?;
    assert_eq!(0, tlv.find_all(&Tag::try_from(0x81_u32)?).len());
    assert_eq!(2, tlv.find_all(&Tag::try_from(0x80_u32)?).len());
    Ok(())
  }
}