yasna/reader/mod.rs
1// Copyright 2016 Masaki Hara
2// Copyright 2017,2019 Fortanix, Inc.
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10#![allow(missing_docs)]
11
12use alloc::vec::Vec;
13use alloc::string::String;
14use alloc::borrow::ToOwned;
15
16mod error;
17
18#[cfg(feature = "num-bigint")]
19use num_bigint::{BigInt,BigUint,Sign};
20#[cfg(feature = "bit-vec")]
21use bit_vec::BitVec;
22
23use super::{PCBit,Tag,TAG_CLASSES};
24use super::tags::{TAG_EOC,TAG_BOOLEAN,TAG_INTEGER,TAG_OCTETSTRING};
25use super::tags::{TAG_NULL,TAG_OID,TAG_UTF8STRING,TAG_SEQUENCE,TAG_SET,TAG_ENUM};
26use super::tags::{TAG_NUMERICSTRING,TAG_PRINTABLESTRING,TAG_VISIBLESTRING,TAG_IA5STRING,TAG_BMPSTRING};
27use super::models::{ObjectIdentifier,TaggedDerValue};
28#[cfg(feature = "time")]
29use super::models::{UTCTime,GeneralizedTime};
30pub use self::error::*;
31
32/// Parses DER/BER-encoded data.
33///
34/// [`parse_ber`] and [`parse_der`] are shorthands
35/// for this function.
36pub fn parse_ber_general<'a, T, F>(buf: &'a [u8], mode: BERMode, callback: F)
37 -> ASN1Result<T>
38 where F: for<'b> FnOnce(BERReader<'a, 'b>) -> ASN1Result<T> {
39 let mut reader_impl = BERReaderImpl::new(buf, mode);
40 let result;
41 {
42 result = callback(BERReader::new(&mut reader_impl))?;
43 }
44 reader_impl.end_of_buf()?;
45 return Ok(result);
46}
47
48/// Parses BER-encoded data.
49///
50/// This function uses the loan pattern: `callback` is called back with
51/// a [`BERReader`], from which the ASN.1 value is read.
52///
53/// If you want to accept only DER-encoded data, use [`parse_der`].
54///
55/// # Examples
56///
57/// ```
58/// use yasna;
59/// let data = &[48, 128, 2, 1, 10, 1, 1, 255, 0, 0];
60/// let asn = yasna::parse_ber(data, |reader| {
61/// reader.read_sequence(|reader| {
62/// let i = reader.next().read_i64()?;
63/// let b = reader.next().read_bool()?;
64/// return Ok((i, b));
65/// })
66/// }).unwrap();
67/// println!("{:?} = [48, 128, 2, 1, 10, 1, 1, 255, 0, 0]", asn);
68/// ```
69pub fn parse_ber<'a, T, F>(buf: &'a [u8], callback: F)
70 -> ASN1Result<T>
71 where F: for<'b> FnOnce(BERReader<'a, 'b>) -> ASN1Result<T> {
72 parse_ber_general(buf, BERMode::Ber, callback)
73}
74
75/// Parses DER-encoded data.
76///
77/// This function uses the loan pattern: `callback` is called back with
78/// a [`BERReader`], from which the ASN.1 value is read.
79///
80/// If you want to parse BER-encoded data in general,
81/// use [`parse_ber`].
82///
83/// # Examples
84///
85/// ```
86/// use yasna;
87/// let data = &[48, 6, 2, 1, 10, 1, 1, 255];
88/// let asn = yasna::parse_der(data, |reader| {
89/// reader.read_sequence(|reader| {
90/// let i = reader.next().read_i64()?;
91/// let b = reader.next().read_bool()?;
92/// return Ok((i, b));
93/// })
94/// }).unwrap();
95/// println!("{:?} = [48, 6, 2, 1, 10, 1, 1, 255]", asn);
96/// ```
97pub fn parse_der<'a, T, F>(buf: &'a [u8], callback: F)
98 -> ASN1Result<T>
99 where F: for<'b> FnOnce(BERReader<'a, 'b>) -> ASN1Result<T> {
100 parse_ber_general(buf, BERMode::Der, callback)
101}
102
103/// Used by [`BERReader`] to determine whether or not to enforce
104/// DER restrictions when parsing.
105#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
106pub enum BERMode {
107 /// Use BER (Basic Encoding Rules).
108 Ber,
109 /// Use DER (Distinguished Encoding Rules).
110 Der,
111}
112
113#[derive(Debug)]
114struct BERReaderImpl<'a> {
115 buf: &'a [u8],
116 pos: usize,
117 mode: BERMode,
118 depth: usize,
119}
120
121const PC_BITS : [PCBit; 2] = [PCBit::Primitive, PCBit::Constructed];
122
123#[derive(Debug)]
124enum Contents<'a, 'b> where 'a: 'b {
125 Primitive(&'a [u8]),
126 Constructed(&'b mut BERReaderImpl<'a>),
127}
128
129const BER_READER_STACK_DEPTH : usize = 100;
130
131impl<'a> BERReaderImpl<'a> {
132 fn new(buf: &'a [u8], mode: BERMode) -> Self {
133 return BERReaderImpl {
134 buf,
135 pos: 0,
136 mode,
137 depth: 0,
138 };
139 }
140
141 fn with_pos(buf: &'a [u8], pos: usize, mode: BERMode) -> Self {
142 return BERReaderImpl {
143 buf,
144 pos,
145 mode,
146 depth: 0,
147 };
148 }
149
150 fn read_u8(&mut self) -> ASN1Result<u8> {
151 if self.pos < self.buf.len() {
152 let ret = self.buf[self.pos];
153 self.pos += 1;
154 return Ok(ret);
155 } else {
156 return Err(ASN1Error::new(ASN1ErrorKind::Eof));
157 }
158 }
159
160 fn end_of_buf(&mut self) -> ASN1Result<()> {
161 if self.pos != self.buf.len() {
162 return Err(ASN1Error::new(ASN1ErrorKind::Extra));
163 }
164 return Ok(());
165 }
166
167 fn end_of_contents(&mut self) -> ASN1Result<()> {
168 let (tag, pcbit) = self.read_identifier()?;
169 if tag != TAG_EOC || pcbit != PCBit::Primitive {
170 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
171 }
172 let b = self.read_u8()?;
173 if b != 0 {
174 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
175 }
176 return Ok(());
177 }
178
179 fn read_identifier(&mut self) -> ASN1Result<(Tag, PCBit)> {
180 let tagbyte = self.read_u8()?;
181 let tag_class = TAG_CLASSES[(tagbyte >> 6) as usize];
182 let pcbit = PC_BITS[((tagbyte >> 5) & 1) as usize];
183 let mut tag_number = (tagbyte & 31) as u64;
184 if tag_number == 31 {
185 tag_number = 0;
186 loop {
187 let b = self.read_u8()? as u64;
188 let x =
189 tag_number.checked_mul(128).ok_or(
190 ASN1Error::new(ASN1ErrorKind::IntegerOverflow))?;
191 tag_number = x + (b & 127);
192 if (b & 128) == 0 {
193 break;
194 }
195 }
196 if tag_number < 31 {
197 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
198 }
199 }
200 let tag = Tag {
201 tag_class,
202 tag_number,
203 };
204 return Ok((tag, pcbit));
205 }
206
207 fn lookahead_tag(&self) -> ASN1Result<Tag> {
208 let mut pos = self.pos;
209 let mut read_u8 = || {
210 if pos < self.buf.len() {
211 let ret = self.buf[pos];
212 pos += 1;
213 return Ok(ret);
214 } else {
215 return Err(ASN1Error::new(ASN1ErrorKind::Eof));
216 }
217 };
218 let tagbyte = read_u8()?;
219 let tag_class = TAG_CLASSES[(tagbyte >> 6) as usize];
220 let mut tag_number = (tagbyte & 31) as u64;
221 if tag_number == 31 {
222 tag_number = 0;
223 loop {
224 let b = read_u8()? as u64;
225 let x =
226 tag_number.checked_mul(128).ok_or(
227 ASN1Error::new(ASN1ErrorKind::IntegerOverflow))?;
228 tag_number = x + (b & 127);
229 if (b & 128) == 0 {
230 break;
231 }
232 }
233 if tag_number < 31 {
234 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
235 }
236 }
237 let tag = Tag {
238 tag_class,
239 tag_number,
240 };
241 return Ok(tag);
242 }
243
244 fn read_length(&mut self) -> ASN1Result<Option<usize>> {
245 let lbyte = self.read_u8()? as usize;
246 if lbyte == 128 {
247 return Ok(None);
248 }
249 if lbyte == 255 {
250 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
251 }
252 if (lbyte & 128) == 0 {
253 return Ok(Some(lbyte));
254 }
255 let mut length : usize = 0;
256 for _ in 0..(lbyte & 127) {
257 let x = length.checked_mul(256).ok_or(
258 ASN1Error::new(ASN1ErrorKind::Eof))?;
259 length = x + (self.read_u8()? as usize);
260 }
261 if self.mode == BERMode::Der && length < 128 {
262 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
263 }
264 return Ok(Some(length));
265 }
266
267 fn read_general<T, F>(&mut self, tag: Tag, callback: F) -> ASN1Result<T>
268 where F: for<'b> FnOnce(Contents<'a, 'b>) -> ASN1Result<T> {
269 if self.depth > BER_READER_STACK_DEPTH {
270 return Err(ASN1Error::new(ASN1ErrorKind::StackOverflow));
271 }
272 let old_pos = self.pos;
273 let (tag2, pcbit) = self.read_identifier()?;
274 if tag2 != tag {
275 self.pos = old_pos;
276 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
277 }
278 let length_spec = self.read_length()?;
279 let old_buf = self.buf;
280 match length_spec {
281 Some(length) => {
282 let limit = match self.pos.checked_add(length) {
283 Some(l) => l,
284 None => return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow)),
285 };
286
287 if old_buf.len() < limit {
288 return Err(ASN1Error::new(ASN1ErrorKind::Eof));
289 }
290 self.buf = &old_buf[..limit];
291 },
292 None => {
293 if pcbit != PCBit::Constructed {
294 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
295 }
296 if self.mode == BERMode::Der {
297 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
298 }
299 },
300 };
301 self.depth += 1;
302 let result = callback(match pcbit {
303 PCBit::Primitive => {
304 let buf = &self.buf[self.pos..];
305 self.pos = self.buf.len();
306 Contents::Primitive(&buf)
307 },
308 PCBit::Constructed => Contents::Constructed(self),
309 })?;
310 self.depth -= 1;
311 match length_spec {
312 Some(_) => {
313 self.end_of_buf()?;
314 },
315 None => {
316 self.end_of_contents()?;
317 },
318 };
319 self.buf = old_buf;
320 return Ok(result);
321 }
322
323 fn skip_general(&mut self) -> ASN1Result<(Tag, PCBit, usize)> {
324 let mut skip_depth = 0;
325 let mut skip_tag = None;
326 let mut data_pos = None;
327 while skip_depth > 0 || skip_tag == None {
328 let old_pos = self.pos;
329 let (tag, pcbit) = self.read_identifier()?;
330 if tag == TAG_EOC {
331 if skip_depth == 0 {
332 self.pos = old_pos;
333 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
334 }
335 skip_depth -= 1;
336 // EOC is a pair of zero bytes, consume the second.
337 if self.read_u8()? != 0 {
338 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
339 }
340 continue;
341 }
342 if skip_depth == 0 {
343 skip_tag = Some((tag, pcbit));
344 }
345 if let Some(length) = self.read_length()? {
346 if skip_depth == 0 {
347 data_pos = Some(self.pos);
348 }
349 let limit = self.pos+length;
350 if self.buf.len() < limit {
351 return Err(ASN1Error::new(ASN1ErrorKind::Eof));
352 }
353 self.pos = limit;
354 } else {
355 if skip_depth == 0 {
356 data_pos = Some(self.pos);
357 }
358 if pcbit != PCBit::Constructed || self.mode == BERMode::Der {
359 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
360 }
361 skip_depth += 1;
362 }
363 }
364 return Ok((skip_tag.unwrap().0, skip_tag.unwrap().1, data_pos.unwrap()));
365 }
366
367 fn read_with_buffer<'b, T, F>(&'b mut self, callback: F)
368 -> ASN1Result<(T, &'a [u8])>
369 where F: FnOnce(&mut Self) -> ASN1Result<T> {
370 let old_pos = self.pos;
371 let result = callback(self)?;
372 let new_pos = self.pos;
373 let buf = &self.buf[old_pos..new_pos];
374 return Ok((result, buf));
375 }
376
377 fn read_optional<T, F>(&mut self, callback: F) -> ASN1Result<Option<T>>
378 where F: FnOnce(&mut Self) -> ASN1Result<T> {
379 let old_pos = self.pos;
380 match callback(self) {
381 Ok(result) => Ok(Some(result)),
382 Err(e) =>
383 if old_pos == self.pos {
384 Ok(None)
385 } else {
386 Err(e)
387 },
388 }
389 }
390
391}
392
393/// A reader object for BER/DER-encoded ASN.1 data.
394///
395/// The two main sources of `BERReaderSeq` are:
396///
397/// - The [`parse_ber`]/[`parse_der`] function,
398/// the starting point of DER serialization.
399/// - The [`next`](BERReaderSeq::next) method of [`BERReaderSeq`].
400///
401/// # Examples
402///
403/// ```
404/// use yasna;
405/// let data = &[2, 1, 10];
406/// let asn = yasna::parse_der(data, |reader| {
407/// reader.read_i64()
408/// }).unwrap();
409/// assert_eq!(asn, 10);
410/// ```
411#[derive(Debug)]
412pub struct BERReader<'a, 'b> where 'a: 'b {
413 inner: &'b mut BERReaderImpl<'a>,
414 implicit_tag: Option<Tag>,
415}
416
417impl<'a, 'b> BERReader<'a, 'b> {
418 fn new(inner: &'b mut BERReaderImpl<'a>) -> Self {
419 BERReader {
420 inner,
421 implicit_tag: None,
422 }
423 }
424
425 fn read_general<T, F>(self, tag: Tag, callback: F) -> ASN1Result<T>
426 where F: for<'c> FnOnce(Contents<'a, 'c>) -> ASN1Result<T> {
427 let tag = self.implicit_tag.unwrap_or(tag);
428 self.inner.read_general(tag, callback)
429 }
430
431 /// Tells which format we are parsing, BER or DER.
432 pub fn mode(&self) -> BERMode {
433 self.inner.mode
434 }
435
436 /// Reads an ASN.1 BOOLEAN value as `bool`.
437 ///
438 /// # Examples
439 ///
440 /// ```
441 /// use yasna;
442 /// let data = &[1, 1, 255];
443 /// let asn = yasna::parse_der(data, |reader| {
444 /// reader.read_bool()
445 /// }).unwrap();
446 /// assert_eq!(asn, true);
447 /// ```
448 pub fn read_bool(self) -> ASN1Result<bool> {
449 let mode = self.mode();
450 self.read_general(TAG_BOOLEAN, |contents| {
451 let buf = match contents {
452 Contents::Primitive(buf) => buf,
453 Contents::Constructed(_) => {
454 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
455 },
456 };
457 if buf.len() != 1 {
458 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
459 }
460 let b = buf[0];
461 if mode == BERMode::Der && b != 0 && b != 255 {
462 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
463 }
464 return Ok(b != 0);
465 })
466 }
467
468 fn read_integer(self, tag: Tag) -> ASN1Result<i64> {
469 self.read_general(tag, |contents| {
470 let buf = match contents {
471 Contents::Primitive(buf) => buf,
472 Contents::Constructed(_) => {
473 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
474 },
475 };
476 if buf.len() == 0 {
477 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
478 } else if buf.len() == 1 {
479 return Ok(buf[0] as i8 as i64);
480 }
481 let mut x = ((buf[0] as i8 as i64) << 8) + (buf[1] as i64);
482 if -128 <= x && x < 128 {
483 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
484 }
485 if buf.len() > 8 {
486 return Err(ASN1Error::new(
487 ASN1ErrorKind::IntegerOverflow));
488 }
489 for &b in buf[2..].iter() {
490 x = (x << 8) | (b as i64);
491 }
492 return Ok(x);
493 })
494 }
495
496 /// Reads an ASN.1 ENUMERATED value as `i64`.
497 ///
498 /// # Examples
499 ///
500 /// ```
501 /// use yasna;
502 /// let data = &[10, 1, 13];
503 /// let asn = yasna::parse_der(data, |reader| {
504 /// reader.read_enum()
505 /// }).unwrap();
506 /// assert_eq!(asn, 13);
507 /// ```
508 ///
509 /// # Errors
510 ///
511 /// Except parse errors, it can raise integer overflow errors.
512 pub fn read_enum(self) -> ASN1Result<i64> {
513 self.read_integer(TAG_ENUM)
514 }
515
516 /// Reads an ASN.1 INTEGER value as `i64`.
517 ///
518 /// # Examples
519 ///
520 /// ```
521 /// use yasna;
522 /// let data = &[2, 4, 73, 150, 2, 210];
523 /// let asn = yasna::parse_der(data, |reader| {
524 /// reader.read_i64()
525 /// }).unwrap();
526 /// assert_eq!(asn, 1234567890);
527 /// ```
528 ///
529 /// # Errors
530 ///
531 /// Except parse errors, it can raise integer overflow errors.
532 pub fn read_i64(self) -> ASN1Result<i64> {
533 self.read_integer(TAG_INTEGER)
534 }
535
536 /// Reads an ASN.1 INTEGER value as `u64`.
537 ///
538 /// # Errors
539 ///
540 /// Except parse errors, it can raise integer overflow errors.
541 pub fn read_u64(self) -> ASN1Result<u64> {
542 self.read_general(TAG_INTEGER, |contents| {
543 let buf = match contents {
544 Contents::Primitive(buf) => buf,
545 Contents::Constructed(_) => {
546 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
547 },
548 };
549 if buf.len() == 0 {
550 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
551 } else if buf[0] >= 128 {
552 return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow));
553 } else if buf.len() == 1 {
554 return Ok(buf[0] as u64);
555 }
556 let mut x = ((buf[0] as u64) << 8) + (buf[1] as u64);
557 if x < 128 {
558 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
559 }
560 if buf.len() > 9 || (buf.len() == 9 && buf[0] != 0) {
561 return Err(ASN1Error::new(
562 ASN1ErrorKind::IntegerOverflow));
563 }
564 for &b in buf[2..].iter() {
565 x = (x << 8) | (b as u64);
566 }
567 return Ok(x);
568 })
569 }
570
571 /// Reads an ASN.1 INTEGER value as `i32`.
572 ///
573 /// # Errors
574 ///
575 /// Except parse errors, it can raise integer overflow errors.
576 pub fn read_i32(self) -> ASN1Result<i32> {
577 let val = self.read_i64()?;
578 if -(1 << 31) <= val && val < (1 << 31) {
579 return Ok(val as i32);
580 } else {
581 return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow));
582 }
583 }
584
585 /// Reads an ASN.1 INTEGER value as `u32`.
586 ///
587 /// # Errors
588 ///
589 /// Except parse errors, it can raise integer overflow errors.
590 pub fn read_u32(self) -> ASN1Result<u32> {
591 let val = self.read_u64()?;
592 if val < (1 << 32) {
593 return Ok(val as u32);
594 } else {
595 return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow));
596 }
597 }
598
599 /// Reads an ASN.1 INTEGER value as `i16`.
600 ///
601 /// # Errors
602 ///
603 /// Except parse errors, it can raise integer overflow errors.
604 pub fn read_i16(self) -> ASN1Result<i16> {
605 let val = self.read_i64()?;
606 if -(1 << 15) <= val && val < (1 << 15) {
607 return Ok(val as i16);
608 } else {
609 return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow));
610 }
611 }
612
613 /// Reads an ASN.1 INTEGER value as `u16`.
614 ///
615 /// # Errors
616 ///
617 /// Except parse errors, it can raise integer overflow errors.
618 pub fn read_u16(self) -> ASN1Result<u16> {
619 let val = self.read_u64()?;
620 if val < (1 << 16) {
621 return Ok(val as u16);
622 } else {
623 return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow));
624 }
625 }
626
627 /// Reads an ASN.1 INTEGER value as `i8`.
628 ///
629 /// # Errors
630 ///
631 /// Except parse errors, it can raise integer overflow errors.
632 pub fn read_i8(self) -> ASN1Result<i8> {
633 let val = self.read_i64()?;
634 if -(1 << 7) <= val && val < (1 << 7) {
635 return Ok(val as i8);
636 } else {
637 return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow));
638 }
639 }
640
641 /// Reads an ASN.1 INTEGER value as `u8`.
642 ///
643 /// # Errors
644 ///
645 /// Except parse errors, it can raise integer overflow errors.
646 pub fn read_u8(self) -> ASN1Result<u8> {
647 let val = self.read_u64()?;
648 if val < (1 << 8) {
649 return Ok(val as u8);
650 } else {
651 return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow));
652 }
653 }
654
655 #[cfg(feature = "num-bigint")]
656 /// Reads an ASN.1 INTEGER value as `BigInt`.
657 ///
658 /// # Examples
659 ///
660 /// ```
661 /// # fn main() {
662 /// use yasna;
663 /// use num_bigint::BigInt;
664 /// let data = &[2, 4, 73, 150, 2, 210];
665 /// let asn = yasna::parse_der(data, |reader| {
666 /// reader.read_bigint()
667 /// }).unwrap();
668 /// assert_eq!(&asn, &BigInt::parse_bytes(b"1234567890", 10).unwrap());
669 /// # }
670 /// ```
671 ///
672 /// # Features
673 ///
674 /// This method is enabled by `num` feature.
675 ///
676 /// ```toml
677 /// [dependencies]
678 /// yasna = { version = "*", features = ["num"] }
679 /// ```
680 pub fn read_bigint(self) -> ASN1Result<BigInt> {
681 let (mut bytes, non_negative) = self.read_bigint_bytes()?;
682 let sign = if non_negative {
683 Sign::Plus
684 } else {
685 let mut carry: usize = 1;
686 for b in bytes.iter_mut().rev() {
687 let bval = 255 - (*b as usize);
688 *b = (bval + carry) as u8;
689 carry = (bval + carry) >> 8;
690 }
691 Sign::Minus
692 };
693 Ok(BigInt::from_bytes_be(sign, &bytes))
694 }
695
696 /// Reads an ASN.1 INTEGER value as `Vec<u8>` and a sign bit.
697 ///
698 /// The number given is in big endian byte ordering, and in two's
699 /// complement.
700 ///
701 /// The sign bit is `true` if the number is positive,
702 /// and false if it is negative.
703 ///
704 /// # Examples
705 ///
706 /// ```
707 /// # fn main() {
708 /// use yasna;
709 /// let data = &[2, 4, 73, 150, 2, 210];
710 /// let (bytes, nonnegative) = yasna::parse_der(data, |reader| {
711 /// reader.read_bigint_bytes()
712 /// }).unwrap();
713 /// assert_eq!(&bytes, &[73, 150, 2, 210]);
714 /// assert_eq!(nonnegative, true);
715 /// # }
716 /// ```
717 pub fn read_bigint_bytes(self) -> ASN1Result<(Vec<u8>, bool)> {
718 self.read_general(TAG_INTEGER, |contents| {
719 let buf = match contents {
720 Contents::Primitive(buf) => buf,
721 Contents::Constructed(_) => {
722 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
723 },
724 };
725 if buf.len() == 0 {
726 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
727 } else if buf.len() == 1 {
728 return Ok((buf.to_vec(), buf[0] & 128 == 0));
729 }
730 let x2 = ((buf[0] as i8 as i32) << 8) + (buf[1] as i32);
731 if -128 <= x2 && x2 < 128 {
732 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
733 }
734 let sign = 0 <= x2;
735 Ok((buf.to_vec(), sign))
736 })
737 }
738
739 #[cfg(feature = "num-bigint")]
740 /// Reads an ASN.1 INTEGER value as `BigUint`.
741 ///
742 /// # Errors
743 ///
744 /// Except parse errors, it can raise integer overflow errors.
745 ///
746 /// # Features
747 ///
748 /// This method is enabled by `num` feature.
749 ///
750 /// ```toml
751 /// [dependencies]
752 /// yasna = { version = "*", features = ["num"] }
753 /// ```
754 pub fn read_biguint(self) -> ASN1Result<BigUint> {
755 self.read_general(TAG_INTEGER, |contents| {
756 let buf = match contents {
757 Contents::Primitive(buf) => buf,
758 Contents::Constructed(_) => {
759 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
760 },
761 };
762 if buf.len() == 0 {
763 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
764 } else if buf[0] >= 128 {
765 return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow));
766 } else if buf.len() == 1 {
767 return Ok(BigUint::from(buf[0]));
768 }
769 let x2 = ((buf[0] as i8 as i32) << 8) + (buf[1] as i32);
770 if -128 <= x2 && x2 < 128 {
771 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
772 } else if x2 < 0 {
773 return Err(ASN1Error::new(ASN1ErrorKind::IntegerOverflow));
774 }
775 return Ok(BigUint::from_bytes_be(buf));
776 })
777 }
778
779 fn read_bitvec_impl(self, unused_bits: &mut usize, bytes: &mut Vec<u8>)
780 -> ASN1Result<()> {
781 use super::tags::TAG_BITSTRING;
782 if *unused_bits != 0 {
783 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
784 }
785 let mode = self.inner.mode;
786 self.read_general(TAG_BITSTRING, |contents| {
787 match contents {
788 Contents::Primitive(buf) => {
789 if buf.len() == 0 {
790 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
791 }
792 if buf[0] >= 8 {
793 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
794 }
795 if buf[0] > 0 {
796 if buf.len() == 1 {
797 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
798 }
799 if mode == BERMode::Der &&
800 (buf[buf.len()-1] & ((1<<buf[0]) - 1)) != 0 {
801 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
802 }
803 }
804 bytes.extend_from_slice(&buf[1..]);
805 *unused_bits = buf[0] as usize;
806 return Ok(());
807 },
808 Contents::Constructed(inner) => {
809 if mode == BERMode::Der {
810 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
811 }
812 loop {
813 let result = inner.read_optional(|inner| {
814 BERReader::new(inner)
815 .read_bitvec_impl(unused_bits, bytes)
816 })?;
817 match result {
818 Some(()) => {},
819 None => { break; },
820 }
821 }
822 return Ok(());
823 },
824 };
825 })
826 }
827
828 #[cfg(feature = "bit-vec")]
829 /// Reads an ASN.1 BITSTRING value as `BitVec`.
830 ///
831 /// # Examples
832 ///
833 /// ```
834 /// # fn main() {
835 /// use yasna;
836 /// use bit_vec::BitVec;
837 /// let data = &[3, 5, 3, 206, 213, 116, 24];
838 /// let asn = yasna::parse_der(data, |reader| {
839 /// reader.read_bitvec()
840 /// }).unwrap();
841 /// assert_eq!(
842 /// asn.into_iter().map(|b| b as usize).collect::<Vec<_>>(),
843 /// vec![1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1,
844 /// 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1]);
845 /// # }
846 /// ```
847 ///
848 /// # Features
849 ///
850 /// This method is enabled by `bit-vec` feature.
851 ///
852 /// ```toml
853 /// [dependencies]
854 /// yasna = { version = "*", features = ["bit-vec"] }
855 /// ```
856 pub fn read_bitvec(self) -> ASN1Result<BitVec> {
857 let (bytes, len) = self.read_bitvec_bytes()?;
858 let mut ret = BitVec::from_bytes(&bytes);
859 ret.truncate(len);
860 return Ok(ret);
861 }
862
863 /// Reads an ASN.1 BITSTRING value as `(Vec<u8>, usize)`.
864 ///
865 /// # Examples
866 ///
867 /// ```
868 /// # fn main() {
869 /// use yasna;
870 /// let data = &[3, 4, 6, 117, 13, 64];
871 /// let asn = yasna::parse_der(data, |reader| {
872 /// reader.read_bitvec_bytes()
873 /// }).unwrap();
874 /// assert_eq!(asn, (vec![117, 13, 64], 18));
875 /// # }
876 /// ```
877 ///
878 /// # Features
879 ///
880 /// This method is enabled by `bit-vec` feature.
881 ///
882 /// ```toml
883 /// [dependencies]
884 /// yasna = { version = "*", features = ["bit-vec"] }
885 /// ```
886 pub fn read_bitvec_bytes(self) -> ASN1Result<(Vec<u8>, usize)> {
887 let mut unused_bits = 0;
888 let mut bytes = Vec::new();
889 self.read_bitvec_impl(&mut unused_bits, &mut bytes)?;
890 let len = bytes.len() * 8 - unused_bits;
891 return Ok((bytes, len));
892 }
893
894 fn read_bytes_impl(self, vec: &mut Vec<u8>) -> ASN1Result<()> {
895 self.read_general(TAG_OCTETSTRING, |contents| {
896 match contents {
897 Contents::Primitive(buf) => {
898 vec.extend(buf);
899 return Ok(());
900 },
901 Contents::Constructed(inner) => {
902 if inner.mode == BERMode::Der {
903 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
904 }
905 loop {
906 let result = inner.read_optional(|inner| {
907 BERReader::new(inner).read_bytes_impl(vec)
908 })?;
909 match result {
910 Some(()) => {},
911 None => { break; },
912 }
913 }
914 return Ok(());
915 },
916 };
917 })
918 }
919
920 /// Reads an ASN.1 OCTETSTRING value as `Vec<u8>`.
921 ///
922 /// # Examples
923 ///
924 /// ```
925 /// use yasna;
926 /// let data = &[36, 128, 4, 2, 72, 101, 4, 4, 108, 108, 111, 33, 0, 0];
927 /// let asn = yasna::parse_ber(data, |reader| {
928 /// reader.read_bytes()
929 /// }).unwrap();
930 /// assert_eq!(&asn, b"Hello!");
931 /// ```
932 pub fn read_bytes(self) -> ASN1Result<Vec<u8>> {
933 let mut ret = Vec::new();
934 self.read_bytes_impl(&mut ret)?;
935 return Ok(ret);
936 }
937
938 /// Reads the ASN.1 NULL value.
939 ///
940 /// # Examples
941 ///
942 /// ```
943 /// use yasna;
944 /// let data = &[5, 0];
945 /// let asn = yasna::parse_der(data, |reader| {
946 /// reader.read_null()
947 /// }).unwrap();
948 /// assert_eq!(asn, ());
949 /// ```
950 pub fn read_null(self) -> ASN1Result<()> {
951 self.read_general(TAG_NULL, |contents| {
952 let buf = match contents {
953 Contents::Primitive(buf) => buf,
954 Contents::Constructed(_) => {
955 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
956 },
957 };
958 if buf.len() != 0 {
959 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
960 }
961 return Ok(());
962 })
963 }
964
965 /// Reads an ASN.1 object identifier.
966 ///
967 /// # Examples
968 ///
969 /// ```
970 /// use yasna;
971 /// let data = &[6, 8, 42, 134, 72, 134, 247, 13, 1, 1];
972 /// let asn = yasna::parse_der(data, |reader| {
973 /// reader.read_oid()
974 /// }).unwrap();
975 /// assert_eq!(&*asn.components(), &[1, 2, 840, 113549, 1, 1]);
976 /// ```
977 pub fn read_oid(self) -> ASN1Result<ObjectIdentifier> {
978 self.read_general(TAG_OID, |contents| {
979 let buf = match contents {
980 Contents::Primitive(buf) => buf,
981 Contents::Constructed(_) => {
982 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
983 },
984 };
985 let mut components = Vec::new();
986 if buf.len() == 0 || buf[buf.len()-1] >= 128 {
987 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
988 }
989 let mut subid : u64 = 0;
990 for &b in buf.iter() {
991 if b == 128 {
992 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
993 }
994 subid = subid.checked_mul(128)
995 .ok_or(ASN1Error::new(
996 ASN1ErrorKind::IntegerOverflow))? + ((b & 127) as u64);
997 if (b & 128) == 0 {
998 if components.len() == 0 {
999 let id0 = if subid < 40 {
1000 0
1001 } else if subid < 80 {
1002 1
1003 } else {
1004 2
1005 };
1006 let id1 = subid - 40 * id0;
1007 components.push(id0);
1008 components.push(id1);
1009 } else {
1010 components.push(subid);
1011 }
1012 subid = 0;
1013 }
1014 }
1015 return Ok(ObjectIdentifier::new(components));
1016 })
1017 }
1018
1019 /// Reads an ASN.1 UTF8String.
1020 ///
1021 /// # Examples
1022 ///
1023 /// ```
1024 /// use yasna;
1025 /// let data = &[
1026 /// 12, 29, 103, 110, 97, 119, 32, 207, 129, 206, 191, 206,
1027 /// 186, 206, 177, 206, 189, 206, 175, 206, 182, 207,
1028 /// 137, 32, 240, 170, 152, 130, 227, 130, 139];
1029 /// let asn = yasna::parse_der(data, |reader| {
1030 /// reader.read_utf8string()
1031 /// }).unwrap();
1032 /// assert_eq!(&asn, "gnaw ροκανίζω 𪘂る");
1033 /// ```
1034 pub fn read_utf8string(self) -> ASN1Result<String> {
1035 self.read_tagged_implicit(TAG_UTF8STRING, |reader| {
1036 let bytes = reader.read_bytes()?;
1037 match String::from_utf8(bytes) {
1038 Ok(string) => Ok(string),
1039 Err(_) => Err(ASN1Error::new(ASN1ErrorKind::Invalid)),
1040 }
1041 })
1042 }
1043
1044 /// Reads an ASN.1 SEQUENCE value.
1045 ///
1046 /// This function uses the loan pattern: `callback` is called back with
1047 /// a [`BERReaderSeq`], from which the contents of the
1048 /// SEQUENCE is read.
1049 ///
1050 /// # Examples
1051 ///
1052 /// ```
1053 /// use yasna;
1054 /// let data = &[48, 6, 2, 1, 10, 1, 1, 255];
1055 /// let asn = yasna::parse_der(data, |reader| {
1056 /// reader.read_sequence(|reader| {
1057 /// let i = reader.next().read_i64()?;
1058 /// let b = reader.next().read_bool()?;
1059 /// return Ok((i, b));
1060 /// })
1061 /// }).unwrap();
1062 /// assert_eq!(asn, (10, true));
1063 /// ```
1064 pub fn read_sequence<T, F>(self, callback: F) -> ASN1Result<T>
1065 where F: for<'c> FnOnce(
1066 &mut BERReaderSeq<'a, 'c>) -> ASN1Result<T> {
1067 self.read_general(TAG_SEQUENCE, |contents| {
1068 let inner = match contents {
1069 Contents::Primitive(_) => {
1070 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1071 },
1072 Contents::Constructed(inner) => inner,
1073 };
1074 return callback(&mut BERReaderSeq { inner, });
1075 })
1076 }
1077
1078 /// Reads an ASN.1 SEQUENCE OF value.
1079 ///
1080 /// This function uses the loan pattern: `callback` is called back with
1081 /// a [`BERReader`], from which the contents of the
1082 /// SEQUENCE OF is read.
1083 ///
1084 /// This function doesn't return values. Instead, use mutable values to
1085 /// maintain read values. `collect_set_of` can be an alternative.
1086 ///
1087 /// # Examples
1088 ///
1089 /// ```
1090 /// use yasna;
1091 /// let data = &[48, 7, 2, 1, 10, 2, 2, 255, 127];
1092 /// let asn = yasna::parse_der(data, |reader| {
1093 /// let mut numbers = Vec::new();
1094 /// reader.read_sequence_of(|reader| {
1095 /// numbers.push(reader.read_i64()?);
1096 /// return Ok(());
1097 /// })?;
1098 /// return Ok(numbers);
1099 /// }).unwrap();
1100 /// assert_eq!(&asn, &[10, -129]);
1101 /// ```
1102 pub fn read_sequence_of<F>(self, mut callback: F) -> ASN1Result<()>
1103 where F: for<'c> FnMut(BERReader<'a, 'c>) -> ASN1Result<()> {
1104 self.read_sequence(|reader| {
1105 loop {
1106 if let None = reader.read_optional(|reader| {
1107 callback(reader)
1108 })? {
1109 break;
1110 }
1111 }
1112 return Ok(());
1113 })
1114 }
1115
1116 /// Collects an ASN.1 SEQUENCE OF value.
1117 ///
1118 /// This function uses the loan pattern: `callback` is called back with
1119 /// a [`BERReader`], from which the contents of the
1120 /// SEQUENCE OF is read.
1121 ///
1122 /// If you don't like `Vec`, you can use `read_sequence_of` instead.
1123 ///
1124 /// # Examples
1125 ///
1126 /// ```
1127 /// use yasna;
1128 /// let data = &[48, 7, 2, 1, 10, 2, 2, 255, 127];
1129 /// let asn = yasna::parse_der(data, |reader| {
1130 /// reader.collect_sequence_of(|reader| {
1131 /// reader.read_i64()
1132 /// })
1133 /// }).unwrap();
1134 /// assert_eq!(&asn, &[10, -129]);
1135 /// ```
1136 pub fn collect_sequence_of<T, F>(self, mut callback: F)
1137 -> ASN1Result<Vec<T>>
1138 where F: for<'c> FnMut(BERReader<'a, 'c>) -> ASN1Result<T> {
1139 let mut collection = Vec::new();
1140 self.read_sequence_of(|reader| {
1141 collection.push(callback(reader)?);
1142 return Ok(());
1143 })?;
1144 return Ok(collection);
1145 }
1146
1147 /// Reads an ASN.1 SET value.
1148 ///
1149 /// This function uses the loan pattern: `callback` is called back with
1150 /// a [`BERReaderSet`], from which the contents of the
1151 /// SET are read.
1152 ///
1153 /// For SET OF values, use `read_set_of` instead.
1154 ///
1155 /// # Examples
1156 ///
1157 /// ```
1158 /// use yasna;
1159 /// use yasna::tags::{TAG_INTEGER,TAG_BOOLEAN};
1160 /// let data = &[49, 6, 1, 1, 255, 2, 1, 10];
1161 /// let asn = yasna::parse_der(data, |reader| {
1162 /// reader.read_set(|reader| {
1163 /// let i = reader.next(&[TAG_INTEGER])?.read_i64()?;
1164 /// let b = reader.next(&[TAG_BOOLEAN])?.read_bool()?;
1165 /// return Ok((i, b));
1166 /// })
1167 /// }).unwrap();
1168 /// assert_eq!(asn, (10, true));
1169 /// ```
1170 pub fn read_set<T, F>(self, callback: F) -> ASN1Result<T>
1171 where F: for<'c> FnOnce(
1172 &mut BERReaderSet<'a, 'c>) -> ASN1Result<T> {
1173 self.read_general(TAG_SET, |contents| {
1174 let inner = match contents {
1175 Contents::Primitive(_) => {
1176 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1177 },
1178 Contents::Constructed(inner) => inner,
1179 };
1180 let mut elements = Vec::new();
1181 loop {
1182 let old_pos = inner.pos;
1183 if let Some(tag) = inner.read_optional(|inner| {
1184 inner.skip_general().map(|t| t.0)
1185 })? {
1186 let new_pos = inner.pos;
1187 // TODO: this should store the P/C bit as well
1188 elements.push((tag, &inner.buf[..new_pos], old_pos));
1189 } else {
1190 break;
1191 }
1192 }
1193 if inner.mode == BERMode::Der {
1194 for i in 1..elements.len() {
1195 if elements[i] <= elements[i-1] {
1196 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1197 }
1198 }
1199 }
1200 let mut new_impl = BERReaderImpl::new(&[], inner.mode);
1201 let result = callback(&mut BERReaderSet {
1202 impl_ref: &mut new_impl,
1203 elements: &mut elements,
1204 })?;
1205 if elements.len() > 0 {
1206 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1207 }
1208 return Ok(result);
1209 })
1210 }
1211
1212 /// Reads an ASN.1 SET OF value.
1213 ///
1214 /// This function uses the loan pattern: `callback` is called back with
1215 /// a [`BERReader`], from which the contents of the
1216 /// SET OF are read.
1217 ///
1218 /// This function doesn't return values. Instead, use mutable values to
1219 /// maintain read values. `collect_set_of` can be an alternative.
1220 ///
1221 /// This function doesn't sort the elements. In DER, it is assumed that
1222 /// the elements occur in an order determined by DER encodings of them.
1223 ///
1224 /// For SET values, use `read_set` instead.
1225 ///
1226 /// # Examples
1227 ///
1228 /// ```
1229 /// use yasna;
1230 /// let data = &[49, 7, 2, 1, 10, 2, 2, 255, 127];
1231 /// let asn = yasna::parse_der(data, |reader| {
1232 /// let mut numbers = Vec::new();
1233 /// reader.read_set_of(|reader| {
1234 /// numbers.push(reader.read_i64()?);
1235 /// return Ok(());
1236 /// })?;
1237 /// return Ok(numbers);
1238 /// }).unwrap();
1239 /// assert_eq!(asn, vec![10, -129]);
1240 /// ```
1241 pub fn read_set_of<F>(self, mut callback: F) -> ASN1Result<()>
1242 where F: for<'c> FnMut(BERReader<'a, 'c>) -> ASN1Result<()> {
1243 self.read_general(TAG_SET, |contents| {
1244 let inner = match contents {
1245 Contents::Primitive(_) => {
1246 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1247 },
1248 Contents::Constructed(inner) => inner,
1249 };
1250 let mut last_buf = None;
1251 while let Some((_, buf)) = inner.read_optional(|inner| {
1252 inner.read_with_buffer(|inner| {
1253 callback(BERReader::new(inner))
1254 })
1255 })? {
1256 if let Some(last_buf) = last_buf {
1257 if inner.mode == BERMode::Der && buf < last_buf {
1258 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1259 }
1260 }
1261 last_buf = Some(buf);
1262 }
1263 return Ok(());
1264 })
1265 }
1266
1267 /// Collects an ASN.1 SET OF value.
1268 ///
1269 /// This function uses the loan pattern: `callback` is called back with
1270 /// a [`BERReader`], from which the contents of the
1271 /// SET OF is read.
1272 ///
1273 /// If you don't like `Vec`, you can use `read_set_of` instead.
1274 ///
1275 /// This function doesn't sort the elements. In DER, it is assumed that
1276 /// the elements occur in an order determined by DER encodings of them.
1277 ///
1278 /// # Examples
1279 ///
1280 /// ```
1281 /// use yasna;
1282 /// let data = &[49, 7, 2, 1, 10, 2, 2, 255, 127];
1283 /// let asn = yasna::parse_der(data, |reader| {
1284 /// reader.collect_set_of(|reader| {
1285 /// reader.read_i64()
1286 /// })
1287 /// }).unwrap();
1288 /// assert_eq!(asn, vec![10, -129]);
1289 /// ```
1290 pub fn collect_set_of<T, F>(self, mut callback: F) -> ASN1Result<Vec<T>>
1291 where F: for<'c> FnMut(BERReader<'a, 'c>) -> ASN1Result<T> {
1292 let mut collection = Vec::new();
1293 self.read_set_of(|reader| {
1294 collection.push(callback(reader)?);
1295 return Ok(());
1296 })?;
1297 return Ok(collection);
1298 }
1299
1300 /// Reads an ASN.1 NumericString.
1301 ///
1302 /// # Examples
1303 ///
1304 /// ```
1305 /// use yasna;
1306 /// let data = &[18, 7, 49, 50, 56, 32, 50, 53, 54];
1307 /// let asn = yasna::parse_der(data, |reader| {
1308 /// reader.read_numeric_string()
1309 /// }).unwrap();
1310 /// assert_eq!(&asn, "128 256");
1311 /// ```
1312 pub fn read_numeric_string(self) -> ASN1Result<String> {
1313 self.read_tagged_implicit(TAG_NUMERICSTRING, |reader| {
1314 let bytes = reader.read_bytes()?;
1315 for &byte in bytes.iter() {
1316 if !(byte == b' ' || (b'0' <= byte && byte <= b'9')) {
1317 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1318 }
1319 }
1320 return Ok(String::from_utf8(bytes).unwrap());
1321 })
1322 }
1323
1324 /// Reads an ASN.1 PrintableString.
1325 ///
1326 /// # Examples
1327 ///
1328 /// ```
1329 /// use yasna;
1330 /// let data = &[19, 9, 67, 111, 46, 44, 32, 76, 116, 100, 46];
1331 /// let asn = yasna::parse_der(data, |reader| {
1332 /// reader.read_printable_string()
1333 /// }).unwrap();
1334 /// assert_eq!(&asn, "Co., Ltd.");
1335 /// ```
1336 pub fn read_printable_string(self) -> ASN1Result<String> {
1337 self.read_tagged_implicit(TAG_PRINTABLESTRING, |reader| {
1338 let bytes = reader.read_bytes()?;
1339 for &byte in bytes.iter() {
1340 if !(
1341 byte == b' ' ||
1342 (b'\'' <= byte && byte <= b':' && byte != b'*') ||
1343 byte == b'=' ||
1344 (b'A' <= byte && byte <= b'Z') ||
1345 (b'a' <= byte && byte <= b'z')) {
1346 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1347 }
1348 }
1349 return Ok(String::from_utf8(bytes).unwrap());
1350 })
1351 }
1352
1353 /// Reads an ASN.1 IA5String.
1354 ///
1355 /// # Examples
1356 ///
1357 /// ```
1358 /// use yasna;
1359 /// let data = &[22, 9, 0x41, 0x53, 0x43, 0x49, 0x49, 0x20, 0x70, 0x6C, 0x7A];
1360 /// let asn = yasna::parse_der(data, |reader| {
1361 /// reader.read_ia5_string()
1362 /// }).unwrap();
1363 /// assert_eq!(&asn, "ASCII plz");
1364 /// ```
1365 pub fn read_ia5_string(self) -> ASN1Result<String> {
1366 self.read_tagged_implicit(TAG_IA5STRING, |reader| {
1367 let bytes = reader.read_bytes()?;
1368
1369 match String::from_utf8(bytes) {
1370 Ok(string) => {
1371 if !string.is_ascii() {
1372 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1373 }
1374 Ok(string)
1375 }
1376 Err(_) => Err(ASN1Error::new(ASN1ErrorKind::Invalid))
1377 }
1378 })
1379 }
1380
1381 /// Reads an ASN.1 BMPString.
1382 ///
1383 /// # Examples
1384 ///
1385 /// ```
1386 /// use yasna;
1387 /// let data = &[30, 14, 0x00, 0xA3, 0x03, 0xC0, 0x00, 0x20, 0x00, 0x71, 0x00, 0x75, 0x00, 0x75, 0x00, 0x78];
1388 /// let asn = yasna::parse_der(data, |reader| {
1389 /// reader.read_bmp_string()
1390 /// }).unwrap();
1391 /// assert_eq!(&asn, "£π quux");
1392 /// ```
1393 pub fn read_bmp_string(self) -> ASN1Result<String> {
1394 self.read_tagged_implicit(TAG_BMPSTRING, |reader| {
1395 let bytes = reader.read_bytes()?;
1396
1397 if bytes.len() % 2 != 0 {
1398 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1399 }
1400
1401 let utf16 : Vec<u16> = bytes.chunks(2).map(|c| (c[0] as u16) * 256 + c[1] as u16).collect();
1402
1403 Ok(String::from_utf16_lossy(&utf16))
1404 })
1405 }
1406
1407 #[cfg(feature = "time")]
1408 /// Reads an ASN.1 UTCTime.
1409 ///
1410 /// # Examples
1411 ///
1412 /// ```
1413 /// use yasna;
1414 /// let data = &[
1415 /// 23, 15, 56, 50, 48, 49, 48, 50, 48,
1416 /// 55, 48, 48, 45, 48, 53, 48, 48];
1417 /// let asn = yasna::parse_ber(data, |reader| {
1418 /// reader.read_utctime()
1419 /// }).unwrap();
1420 /// assert_eq!(asn.datetime().unix_timestamp(), 378820800);
1421 /// ```
1422 ///
1423 /// # Features
1424 ///
1425 /// This method is enabled by `time` feature.
1426 ///
1427 /// ```toml
1428 /// [dependencies]
1429 /// yasna = { version = "*", features = ["time"] }
1430 /// ```
1431 pub fn read_utctime(self) -> ASN1Result<UTCTime> {
1432 use super::tags::TAG_UTCTIME;
1433 let mode = self.inner.mode;
1434 self.read_tagged_implicit(TAG_UTCTIME, |reader| {
1435 let bytes = reader.read_bytes()?;
1436 let datetime = UTCTime::parse(&bytes).ok_or_else(
1437 || ASN1Error::new(ASN1ErrorKind::Invalid))?;
1438 if mode == BERMode::Der && &datetime.to_bytes() != &bytes {
1439 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1440 }
1441 return Ok(datetime);
1442 })
1443 }
1444
1445 #[cfg(feature = "time")]
1446 /// Reads an ASN.1 GeneralizedTime.
1447 ///
1448 /// # Examples
1449 ///
1450 /// ```
1451 /// use yasna;
1452 /// let data = &[
1453 /// 24, 17, 49, 57, 56, 53, 49, 49, 48, 54,
1454 /// 50, 49, 46, 49, 52, 49, 53, 57, 90];
1455 /// let asn = yasna::parse_ber(data, |reader| {
1456 /// reader.read_generalized_time()
1457 /// }).unwrap();
1458 /// assert_eq!(asn.datetime().unix_timestamp(), 500159309);
1459 /// ```
1460 ///
1461 /// # Features
1462 ///
1463 /// This method is enabled by `time` feature.
1464 ///
1465 /// ```toml
1466 /// [dependencies]
1467 /// yasna = { version = "*", features = ["time"] }
1468 /// ```
1469 pub fn read_generalized_time(self) -> ASN1Result<GeneralizedTime> {
1470 use super::tags::TAG_GENERALIZEDTIME;
1471 let mode = self.inner.mode;
1472 self.read_tagged_implicit(TAG_GENERALIZEDTIME, |reader| {
1473 let bytes = reader.read_bytes()?;
1474 let datetime = GeneralizedTime::parse(&bytes).ok_or_else(
1475 || ASN1Error::new(ASN1ErrorKind::Invalid))?;
1476 if mode == BERMode::Der && &datetime.to_bytes() != &bytes {
1477 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1478 }
1479 return Ok(datetime);
1480 })
1481 }
1482
1483 /// Reads an ASN.1 VisibleString.
1484 ///
1485 /// # Examples
1486 ///
1487 /// ```
1488 /// use yasna;
1489 /// let data = &[26, 3, 72, 105, 33];
1490 /// let asn = yasna::parse_der(data, |reader| {
1491 /// reader.read_visible_string()
1492 /// }).unwrap();
1493 /// assert_eq!(&asn, "Hi!");
1494 /// ```
1495 pub fn read_visible_string(self) -> ASN1Result<String> {
1496 self.read_tagged_implicit(TAG_VISIBLESTRING, |reader| {
1497 let bytes = reader.read_bytes()?;
1498 for &byte in bytes.iter() {
1499 if !(b' ' <= byte && byte <= b'~') {
1500 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1501 }
1502 }
1503 return Ok(String::from_utf8(bytes).unwrap());
1504 })
1505 }
1506
1507 /// Reads a (explicitly) tagged value.
1508 ///
1509 /// # Examples
1510 ///
1511 /// ```
1512 /// use yasna::{self,Tag};
1513 /// let data = &[163, 3, 2, 1, 10];
1514 /// let asn = yasna::parse_der(data, |reader| {
1515 /// reader.read_tagged(Tag::context(3), |reader| {
1516 /// reader.read_i64()
1517 /// })
1518 /// }).unwrap();
1519 /// assert_eq!(asn, 10);
1520 /// ```
1521 pub fn read_tagged<T, F>(self, tag: Tag, callback: F) -> ASN1Result<T>
1522 where F: for<'c> FnOnce(BERReader<'a, 'c>) -> ASN1Result<T> {
1523 self.read_general(tag, |contents| {
1524 let inner = match contents {
1525 Contents::Primitive(_) => {
1526 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1527 },
1528 Contents::Constructed(inner) => inner,
1529 };
1530 callback(BERReader::new(inner))
1531 })
1532 }
1533
1534 /// Reads an implicitly tagged value.
1535 ///
1536 /// # Examples
1537 ///
1538 /// ```
1539 /// use yasna::{self,Tag};
1540 /// let data = &[131, 1, 10];
1541 /// let asn = yasna::parse_der(data, |reader| {
1542 /// reader.read_tagged_implicit(Tag::context(3), |reader| {
1543 /// reader.read_i64()
1544 /// })
1545 /// }).unwrap();
1546 /// assert_eq!(asn, 10);
1547 /// ```
1548 pub fn read_tagged_implicit<T, F>(self, tag: Tag, callback: F)
1549 -> ASN1Result<T>
1550 where F: for<'c> FnOnce(BERReader<'a, 'c>) -> ASN1Result<T> {
1551 let tag = self.implicit_tag.unwrap_or(tag);
1552 return callback(BERReader {
1553 inner: self.inner,
1554 implicit_tag: Some(tag),
1555 });
1556 }
1557
1558 /// Lookaheads the tag in the next value. Used to parse CHOICE values.
1559 ///
1560 /// # Examples
1561 ///
1562 /// ```
1563 /// use yasna;
1564 /// use yasna::tags::*;
1565 /// let data = &[48, 5, 2, 1, 10, 5, 0];
1566 /// let asn = yasna::parse_der(data, |reader| {
1567 /// reader.collect_sequence_of(|reader| {
1568 /// let tag = reader.lookahead_tag()?;
1569 /// let choice;
1570 /// if tag == TAG_INTEGER {
1571 /// choice = Some(reader.read_i64()?);
1572 /// } else {
1573 /// reader.read_null()?;
1574 /// choice = None;
1575 /// }
1576 /// return Ok(choice);
1577 /// })
1578 /// }).unwrap();
1579 /// assert_eq!(&asn, &[Some(10), None]);
1580 /// ```
1581 pub fn lookahead_tag(&self) -> ASN1Result<Tag> {
1582 self.inner.lookahead_tag()
1583 }
1584
1585 pub fn read_with_buffer<T, F>(self, callback: F)
1586 -> ASN1Result<(T, &'a [u8])>
1587 where F: for<'c> FnOnce(BERReader<'a, 'c>) -> ASN1Result<T> {
1588 let implicit_tag = self.implicit_tag;
1589 self.inner.read_with_buffer(|inner| {
1590 callback(BERReader {
1591 inner,
1592 implicit_tag,
1593 })
1594 })
1595 }
1596
1597 /// Read an arbitrary (tag, value) pair as a TaggedDerValue.
1598 /// The length is not included in the returned payload. If the
1599 /// payload has indefinite-length encoding, the EOC bytes are
1600 /// included in the returned payload.
1601 ///
1602 /// # Examples
1603 ///
1604 /// ```
1605 /// use yasna;
1606 /// use yasna::models::TaggedDerValue;
1607 /// use yasna::tags::TAG_OCTETSTRING;
1608 /// let data = b"\x04\x06Hello!";
1609 /// let res = yasna::parse_der(data, |reader| reader.read_tagged_der()).unwrap();
1610 /// assert_eq!(res, TaggedDerValue::from_tag_and_bytes(TAG_OCTETSTRING, b"Hello!".to_vec()));
1611 /// ```
1612 pub fn read_tagged_der(self) -> ASN1Result<TaggedDerValue> {
1613 let (tag, pcbit, data_pos) = self.inner.skip_general()?;
1614 Ok(TaggedDerValue::from_tag_pc_and_bytes(
1615 tag,
1616 pcbit,
1617 self.inner.buf[data_pos..self.inner.pos].to_vec()))
1618 }
1619
1620 /// Reads a DER object as raw bytes. Tag and length are included
1621 /// in the returned buffer. For indefinite length encoding, EOC bytes
1622 /// are included in the returned buffer as well.
1623 ///
1624 /// # Examples
1625 ///
1626 /// ```
1627 /// use yasna;
1628 /// let data = b"\x04\x06Hello!";
1629 /// let res = yasna::parse_der(data, |reader| reader.read_der()).unwrap();
1630 /// assert_eq!(res, data);
1631 /// ```
1632 pub fn read_der(self) -> ASN1Result<Vec<u8>> {
1633 Ok(self.inner.read_with_buffer(|inner| {
1634 inner.skip_general()
1635 })?.1.to_owned())
1636 }
1637}
1638
1639/// A reader object for a sequence of BER/DER-encoded ASN.1 data.
1640///
1641/// The main source of this object is the [`read_sequence`] method from
1642/// [`BERReader`].
1643///
1644/// [`read_sequence`]: BERReader::read_sequence
1645///
1646/// # Examples
1647///
1648/// ```
1649/// use yasna;
1650/// let data = &[48, 6, 2, 1, 10, 1, 1, 255];
1651/// let asn = yasna::parse_der(data, |reader| {
1652/// reader.read_sequence(|reader| {
1653/// let i = reader.next().read_i64()?;
1654/// let b = reader.next().read_bool()?;
1655/// return Ok((i, b));
1656/// })
1657/// }).unwrap();
1658/// assert_eq!(asn, (10, true));
1659/// ```
1660#[derive(Debug)]
1661pub struct BERReaderSeq<'a, 'b> where 'a: 'b {
1662 inner: &'b mut BERReaderImpl<'a>,
1663}
1664
1665impl<'a, 'b> BERReaderSeq<'a, 'b> {
1666 /// Tells which format we are parsing, BER or DER.
1667 pub fn mode(&self) -> BERMode {
1668 self.inner.mode
1669 }
1670
1671 /// Generates a new [`BERReader`].
1672 pub fn next<'c>(&'c mut self) -> BERReader<'a, 'c> {
1673 BERReader::new(self.inner)
1674 }
1675
1676 /// Tries to read an ASN.1 value. If it fails at the first tag,
1677 /// it doesn't consume buffer and returns `None`.
1678 ///
1679 /// Used to parse OPTIONAL elements.
1680 ///
1681 /// # Examples
1682 ///
1683 /// ```
1684 /// use yasna;
1685 /// let data = &[48, 3, 1, 1, 255];
1686 /// let asn = yasna::parse_der(data, |reader| {
1687 /// reader.read_sequence(|reader| {
1688 /// let i = reader.read_optional(|reader| {
1689 /// reader.read_i64()
1690 /// })?;
1691 /// let b = reader.next().read_bool()?;
1692 /// return Ok((i, b));
1693 /// })
1694 /// }).unwrap();
1695 /// assert_eq!(asn, (None, true));
1696 /// ```
1697 pub fn read_optional<T, F>(&mut self, callback: F)
1698 -> ASN1Result<Option<T>>
1699 where F: for<'c> FnOnce(BERReader<'a, 'c>) -> ASN1Result<T> {
1700 self.inner.read_optional(|inner| {
1701 callback(BERReader::new(inner))
1702 })
1703 }
1704
1705 /// Similar to [`read_optional`](Self::read_optional),
1706 /// but uses `default` if it fails.
1707 ///
1708 /// `T: Eq` is required because it fails in DER mode if the read value
1709 /// is equal to `default`.
1710 ///
1711 /// Used to parse DEFAULT elements.
1712 ///
1713 /// # Examples
1714 ///
1715 /// ```
1716 /// use yasna;
1717 /// let data = &[48, 3, 1, 1, 255];
1718 /// let asn = yasna::parse_der(data, |reader| {
1719 /// reader.read_sequence(|reader| {
1720 /// let i = reader.read_default(10, |reader| {
1721 /// reader.read_i64()
1722 /// })?;
1723 /// let b = reader.next().read_bool()?;
1724 /// return Ok((i, b));
1725 /// })
1726 /// }).unwrap();
1727 /// assert_eq!(asn, (10, true));
1728 /// ```
1729 pub fn read_default<T, F>(&mut self, default: T, callback: F)
1730 -> ASN1Result<T>
1731 where F: for<'c> FnOnce(BERReader<'a, 'c>) -> ASN1Result<T>,
1732 T: Eq {
1733 match self.read_optional(callback)? {
1734 Some(result) => {
1735 if self.inner.mode == BERMode::Der && result == default {
1736 return Err(
1737 ASN1Error::new(ASN1ErrorKind::Invalid));
1738 }
1739 return Ok(result);
1740 },
1741 None => Ok(default),
1742 }
1743 }
1744
1745 pub fn read_with_buffer<T, F>(&mut self, callback: F)
1746 -> ASN1Result<(T, &'a [u8])>
1747 where F: for<'c> FnOnce(
1748 &mut BERReaderSeq<'a, 'c>) -> ASN1Result<T> {
1749 self.inner.read_with_buffer(|inner| {
1750 callback(&mut BERReaderSeq { inner, })
1751 })
1752 }
1753}
1754
1755/// A reader object for a set of BER/DER-encoded ASN.1 data.
1756///
1757/// The main source of this object is the [`read_set`](BERReader::read_set)
1758/// method from [`BERReader`].
1759///
1760/// # Examples
1761///
1762/// ```
1763/// use yasna;
1764/// use yasna::tags::{TAG_INTEGER,TAG_BOOLEAN};
1765/// let data = &[49, 6, 1, 1, 255, 2, 1, 10];
1766/// let asn = yasna::parse_der(data, |reader| {
1767/// reader.read_set(|reader| {
1768/// let i = reader.next(&[TAG_INTEGER])?.read_i64()?;
1769/// let b = reader.next(&[TAG_BOOLEAN])?.read_bool()?;
1770/// return Ok((i, b));
1771/// })
1772/// }).unwrap();
1773/// assert_eq!(asn, (10, true));
1774/// ```
1775#[derive(Debug)]
1776pub struct BERReaderSet<'a, 'b> where 'a: 'b {
1777 impl_ref: &'b mut BERReaderImpl<'a>,
1778 elements: &'b mut Vec<(Tag, &'a [u8], usize)>,
1779}
1780
1781impl<'a, 'b> BERReaderSet<'a, 'b> {
1782 /// Tells which format we are parsing, BER or DER.
1783 pub fn mode(&self) -> BERMode {
1784 self.impl_ref.mode
1785 }
1786
1787 /// Generates a new [`BERReader`].
1788 ///
1789 /// This method needs `tag_hint` to determine the position of the data.
1790 pub fn next<'c>(&'c mut self, tag_hint: &[Tag])
1791 -> ASN1Result<BERReader<'a, 'c>> {
1792 if let Some(elem_pos) = self.elements.iter().position(|&(tag,_,_)| {
1793 tag_hint.contains(&tag)
1794 }) {
1795 let (_, buf, pos) = self.elements.remove(elem_pos);
1796 *self.impl_ref = BERReaderImpl::with_pos(
1797 buf, pos, self.impl_ref.mode);
1798 return Ok(BERReader::new(self.impl_ref))
1799 } else {
1800 return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
1801 }
1802 }
1803
1804 /// If there is a set element with a tag in `tag_hint`, reads an ASN.1
1805 /// value from that element and returns `Some(_)`.
1806 /// Otherwise, returns `None`.
1807 ///
1808 /// Used to parse OPTIONAL elements.
1809 ///
1810 /// # Examples
1811 ///
1812 /// ```
1813 /// use yasna;
1814 /// use yasna::tags::*;
1815 /// let data = &[49, 3, 1, 1, 255];
1816 /// let asn = yasna::parse_der(data, |reader| {
1817 /// reader.read_set(|reader| {
1818 /// let i = reader.read_optional(&[TAG_INTEGER], |reader| {
1819 /// reader.read_i64()
1820 /// })?;
1821 /// let b = reader.next(&[TAG_BOOLEAN])?.read_bool()?;
1822 /// return Ok((i, b));
1823 /// })
1824 /// }).unwrap();
1825 /// assert_eq!(asn, (None, true));
1826 /// ```
1827 pub fn read_optional<T, F>(&mut self, tag_hint: &[Tag], callback: F)
1828 -> ASN1Result<Option<T>>
1829 where F: for<'c> FnOnce(BERReader<'a, 'c>) -> ASN1Result<T> {
1830 if let Some(elem_pos) = self.elements.iter().position(|&(tag,_,_)| {
1831 tag_hint.contains(&tag)
1832 }) {
1833 let (_, buf, pos) = self.elements.remove(elem_pos);
1834 let mut reader_impl = BERReaderImpl::with_pos(
1835 buf, pos, self.impl_ref.mode);
1836 let result = callback(BERReader::new(&mut reader_impl))?;
1837 reader_impl.end_of_buf()?;
1838 return Ok(Some(result));
1839 } else {
1840 return Ok(None);
1841 }
1842 }
1843
1844 /// Similar to [`read_optional`](Self::read_optional),
1845 /// but uses `default` if it fails.
1846 ///
1847 /// `T: Eq` is required because it fails in DER mode if the read value
1848 /// is equal to `default`.
1849 ///
1850 /// Used to parse DEFAULT elements.
1851 ///
1852 /// # Examples
1853 ///
1854 /// ```
1855 /// use yasna;
1856 /// use yasna::tags::*;
1857 /// let data = &[49, 3, 1, 1, 255];
1858 /// let asn = yasna::parse_der(data, |reader| {
1859 /// reader.read_set(|reader| {
1860 /// let i = reader.read_default(&[TAG_INTEGER], 10, |reader| {
1861 /// reader.read_i64()
1862 /// })?;
1863 /// let b = reader.next(&[TAG_BOOLEAN])?.read_bool()?;
1864 /// return Ok((i, b));
1865 /// })
1866 /// }).unwrap();
1867 /// assert_eq!(asn, (10, true));
1868 /// ```
1869 pub fn read_default<T, F>
1870 (&mut self, tag_hint: &[Tag], default: T, callback: F)
1871 -> ASN1Result<T>
1872 where F: for<'c> FnOnce(BERReader<'a, 'c>) -> ASN1Result<T>,
1873 T: Eq {
1874 let mode = self.impl_ref.mode;
1875 match self.read_optional(tag_hint, callback)? {
1876 Some(result) => {
1877 if mode == BERMode::Der && result == default {
1878 return Err(
1879 ASN1Error::new(ASN1ErrorKind::Invalid));
1880 }
1881 return Ok(result);
1882 },
1883 None => Ok(default),
1884 }
1885 }
1886}
1887
1888
1889#[cfg(test)]
1890mod tests;