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
use std::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
  /// 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(Tlv { tag, value: value })
  }

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

  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() + Tlv::len_length(inner_len as u32) + inner_len
  }

  /// serializes self into a byte vector.
  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 {
      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;
      }
    } else {
      ret = x as usize;
    }
    Ok(ret)
  }

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

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

  /// 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));
    (
      Tlv::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.
  pub fn from_bytes(input: &[u8]) -> Result<Self> {
    let (r, n) = Tlv::parse(input);
    if n.len() != 0 {
      Err(TlvError::InvalidInput)
    } else {
      r
    }
  }
}

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 std::convert::TryFrom;

  #[test]
  fn tlv_to_from_vec_primitive() {
    let tlv = Tlv::new(Tag::try_from(1u32).unwrap(), Value::Primitive(vec![0])).unwrap();
    assert_eq!(vec![1, 1, 0], tlv.to_vec());
    {
      let mut data = vec![0u8; 255];
      let tlv = Tlv::new(Tag::try_from(1u32).unwrap(), Value::Primitive(data.clone())).unwrap();
      let mut expected = vec![1u8, 0x81, 0xFF];
      expected.append(&mut data);
      assert_eq!(expected, tlv.to_vec());

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

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

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

  #[test]
  fn tlv_to_from_vec_constructed() {
    let base = Tlv::new(Tag::try_from(1u32).unwrap(), Value::Primitive(vec![0])).unwrap();
    let mut construct = Value::Constructed(vec![base.clone(), base.clone(), base.clone()]);

    let tlv = Tlv::new(Tag::try_from("7f22").unwrap(), construct.clone()).unwrap();
    let mut expected = vec![0x7fu8, 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());

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

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

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

    println!("{}", tlv)
  }

  #[test]
  fn parse() {
    let primitive_bytes = vec![1, 1, 0];
    let more_bytes = vec![1u8; 10];
    let mut input = vec![0x7fu8, 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.unwrap().to_vec());
    assert_eq!(more_bytes, left);
  }

  #[test]
  fn display() {
    let base = Tlv::new(Tag::try_from(0x80u32).unwrap(), Value::Primitive(vec![0])).unwrap();
    let construct = Value::Constructed(vec![base.clone(), base.clone()]);
    let tlv = Tlv::new(Tag::try_from("7f22").unwrap(), construct.clone()).unwrap();

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

}