-
Notifications
You must be signed in to change notification settings - Fork 23
/
lib.rs
1645 lines (1465 loc) · 55 KB
/
lib.rs
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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A small ASN.1 parsing library for Rust. In particular, this library is used
//! to translate the binary DER encoding of an ASN.1-formatted document into the
//! core primitives of ASN.1. It is assumed that you can do what you need to
//! from there.
//!
//! The critical items for this document are the traits `ToASN1` and `FromASN1`.
//! The first takes your data type and encodes it into a `Vec` of simple ASN.1
//! structures (`ASN1Block`s). The latter inverts the process.
//!
//! Items that implement `ToASN1` can be used with the function `der_encode`
//! to provide single-step encoding of a data type to binary DER encoding.
//! Similarly, items that are `FromASN` can be single-step decoded using
//! the helper function `der_decode`.
//!
//! You can implement one or both traits, depending on your needs. If you do
//! implement both, the obvious encode/decode quickcheck property is strongly
//! advised.
//!
//! For decoding schemes that require the actual bytes associated with the
//! binary representation, we also provide `FromASN1WithBody`. This can be
//! used with the offset information in the primitive `ASN1Block`s to, for
//! example, validate signatures in X509 documents.
//!
//! Finally, this library supports ASN.1 class information. I'm still not sure
//! why it's useful, but there it is.
//!
//! Please send any bug reports, patches, and curses to the GitHub repository
//! at <code>https://github.com/acw/simple_asn1</code>.
extern crate chrono;
extern crate num_bigint;
extern crate num_traits;
#[cfg(test)]
#[macro_use]
extern crate quickcheck;
#[cfg(test)]
extern crate rand;
use chrono::{DateTime, TimeZone, Utc};
pub use num_bigint::{BigInt, BigUint};
use num_traits::{FromPrimitive, One, ToPrimitive, Zero};
use std::error::Error;
use std::fmt;
use std::iter::FromIterator;
use std::mem::size_of;
use std::str::Utf8Error;
/// An ASN.1 block class.
///
/// I'm not sure if/when these are used, but here they are in case you want
/// to do something with them.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ASN1Class {
Universal,
Application,
ContextSpecific,
Private,
}
/// A primitive block from ASN.1.
///
/// Primitive blocks all contain the offset from the beginning of the parsed
/// document, followed by whatever data is associated with the block. The latter
/// should be fairly self-explanatory, so let's discuss the offset.
///
/// The offset is only valid during the reading process. It is ignored for
/// the purposes of encoding blocks into their binary form. It is also
/// ignored for the purpose of comparisons via `==`. It is included entirely
/// to support the parsing of things like X509 certificates, in which it is
/// necessary to know when particular blocks end.
///
/// The [`ASN1Class`] of explicitly tagged blocks is either `Application`,
/// `ContextSpecific` or `Private`. `Unknown` can have any class.
/// The class of all other variants is `Universal`.
///
/// [`ASN1Class`]: enum.ASN1Class.html
#[derive(Clone, Debug)]
pub enum ASN1Block {
Boolean(usize, bool),
Integer(usize, BigInt),
BitString(usize, usize, Vec<u8>),
OctetString(usize, Vec<u8>),
Null(usize),
ObjectIdentifier(usize, OID),
UTF8String(usize, String),
PrintableString(usize, String),
TeletexString(usize, String),
IA5String(usize, String),
UTCTime(usize, DateTime<Utc>),
GeneralizedTime(usize, DateTime<Utc>),
UniversalString(usize, String),
BMPString(usize, String),
Sequence(usize, Vec<ASN1Block>),
Set(usize, Vec<ASN1Block>),
/// An explicitly tagged block.
///
/// The class can be either `Application`, `ContextSpecific` or `Private`.
/// The other parameters are `offset`, `tag` and `content`.
///
/// This block is always `constructed`.
Explicit(ASN1Class, usize, BigUint, Box<ASN1Block>),
/// An unkown block.
///
/// The parameters are `class`, `constructed`, `offset`, `tag` and
/// `content`.
Unknown(ASN1Class, bool, usize, BigUint, Vec<u8>),
}
impl ASN1Block {
/// Get the class associated with the given ASN1Block, regardless of what
/// kind of block it is.
pub fn class(&self) -> ASN1Class {
match self {
&ASN1Block::Boolean(_,_) => ASN1Class::Universal,
&ASN1Block::Integer(_,_) => ASN1Class::Universal,
&ASN1Block::BitString(_,_,_) => ASN1Class::Universal,
&ASN1Block::OctetString(_,_) => ASN1Class::Universal,
&ASN1Block::Null(_) => ASN1Class::Universal,
&ASN1Block::ObjectIdentifier(_,_) => ASN1Class::Universal,
&ASN1Block::UTF8String(_,_) => ASN1Class::Universal,
&ASN1Block::PrintableString(_,_) => ASN1Class::Universal,
&ASN1Block::TeletexString(_,_) => ASN1Class::Universal,
&ASN1Block::IA5String(_,_) => ASN1Class::Universal,
&ASN1Block::UTCTime(_,_) => ASN1Class::Universal,
&ASN1Block::GeneralizedTime(_,_) => ASN1Class::Universal,
&ASN1Block::UniversalString(_,_) => ASN1Class::Universal,
&ASN1Block::BMPString(_,_) => ASN1Class::Universal,
&ASN1Block::Sequence(_,_) => ASN1Class::Universal,
&ASN1Block::Set(_,_) => ASN1Class::Universal,
&ASN1Block::Explicit(c,_,_,_) => c,
&ASN1Block::Unknown(c,_,_,_,_) => c,
}
}
/// Get the starting offset associated with the given ASN1Block, regardless
/// of what kind of block it is.
pub fn offset(&self) -> usize {
match self {
&ASN1Block::Boolean(o,_) => o,
&ASN1Block::Integer(o,_) => o,
&ASN1Block::BitString(o,_,_) => o,
&ASN1Block::OctetString(o,_) => o,
&ASN1Block::Null(o) => o,
&ASN1Block::ObjectIdentifier(o,_) => o,
&ASN1Block::UTF8String(o,_) => o,
&ASN1Block::PrintableString(o,_) => o,
&ASN1Block::TeletexString(o,_) => o,
&ASN1Block::IA5String(o,_) => o,
&ASN1Block::UTCTime(o,_) => o,
&ASN1Block::GeneralizedTime(o,_) => o,
&ASN1Block::UniversalString(o,_) => o,
&ASN1Block::BMPString(o,_) => o,
&ASN1Block::Sequence(o,_) => o,
&ASN1Block::Set(o,_) => o,
&ASN1Block::Explicit(_,o,_,_) => o,
&ASN1Block::Unknown(_,_,o,_,_) => o,
}
}
}
impl PartialEq for ASN1Block {
fn eq(&self, other: &ASN1Block) -> bool {
match (self, other) {
(&ASN1Block::Boolean(_,a1),
&ASN1Block::Boolean(_,a2)) =>
(a1 == a2),
(&ASN1Block::Integer(_,ref a1),
&ASN1Block::Integer(_,ref a2)) =>
(a1 == a2),
(&ASN1Block::BitString(_,a1,ref b1),
&ASN1Block::BitString(_,a2,ref b2)) =>
(a1 == a2) && (b1 == b2),
(&ASN1Block::OctetString(_,ref a1),
&ASN1Block::OctetString(_,ref a2)) =>
(a1 == a2),
(&ASN1Block::Null(_),
&ASN1Block::Null(_)) =>
true,
(&ASN1Block::ObjectIdentifier(_,ref a1),
&ASN1Block::ObjectIdentifier(_,ref a2)) =>
(a1 == a2),
(&ASN1Block::UTF8String(_,ref a1),
&ASN1Block::UTF8String(_,ref a2)) =>
(a1 == a2),
(&ASN1Block::PrintableString(_,ref a1),
&ASN1Block::PrintableString(_,ref a2)) =>
(a1 == a2),
(&ASN1Block::TeletexString(_,ref a1),
&ASN1Block::TeletexString(_,ref a2)) =>
(a1 == a2),
(&ASN1Block::IA5String(_,ref a1),
&ASN1Block::IA5String(_,ref a2)) =>
(a1 == a2),
(&ASN1Block::UTCTime(_,ref a1),
&ASN1Block::UTCTime(_,ref a2)) =>
(a1 == a2),
(&ASN1Block::GeneralizedTime(_,ref a1),
&ASN1Block::GeneralizedTime(_,ref a2)) =>
(a1 == a2),
(&ASN1Block::UniversalString(_,ref a1),
&ASN1Block::UniversalString(_,ref a2)) =>
(a1 == a2),
(&ASN1Block::BMPString(_,ref a1),
&ASN1Block::BMPString(_,ref a2)) =>
(a1 == a2),
(&ASN1Block::Sequence(_,ref a1),
&ASN1Block::Sequence(_,ref a2)) =>
(a1 == a2),
(&ASN1Block::Set(_,ref a1),
&ASN1Block::Set(_,ref a2)) =>
(a1 == a2),
(&ASN1Block::Explicit(a1,_,ref b1,ref c1),
&ASN1Block::Explicit(a2,_,ref b2,ref c2)) =>
(a1 == a2) && (b1 == b2) && (c1 == c2),
(&ASN1Block::Unknown(a1,b1,_,ref c1,ref d1),
&ASN1Block::Unknown(a2,b2,_,ref c2,ref d2)) =>
(a1 == a2) && (b1 == b2) && (c1 == c2) && (d1 == d2),
_ =>
false
}
}
}
/// An ASN.1 OID.
#[derive(Clone, Debug, PartialEq)]
pub struct OID(Vec<BigUint>);
impl OID {
/// Generate an ASN.1. The vector should be in the obvious format,
/// with each component going left-to-right.
pub fn new(x: Vec<BigUint>) -> OID {
OID(x)
}
/// converts the
pub fn as_raw(&self) -> Result<Vec<u8>, ASN1EncodeErr> {
match (self.0.get(0), self.0.get(1)) {
(Some(v1), Some(v2)) => {
let two = BigUint::from_u8(2).unwrap();
// first, validate that the first two items meet spec
if v1 > &two {
return Err(ASN1EncodeErr::ObjectIdentVal1TooLarge);
}
let u175 = BigUint::from_u8(175).unwrap();
let u39 = BigUint::from_u8(39).unwrap();
let bound = if v1 == &two { u175 } else { u39 };
if v2 > &bound {
return Err(ASN1EncodeErr::ObjectIdentVal2TooLarge);
}
// the following unwraps must be safe, based on the
// validation above.
let value1 = v1.to_u8().unwrap();
let value2 = v2.to_u8().unwrap();
let byte1 = (value1 * 40) + value2;
// now we can build all the rest of the body
let mut body = vec![byte1];
for num in self.0.iter().skip(2) {
let mut local = encode_base127(&num);
body.append(&mut local);
}
Ok(body)
}
_ => Err(ASN1EncodeErr::ObjectIdentHasTooFewFields),
}
}
}
impl<'a> PartialEq<OID> for &'a OID {
fn eq(&self, v2: &OID) -> bool {
let &&OID(ref vec1) = self;
let &OID(ref vec2) = v2;
if vec1.len() != vec2.len() {
return false;
}
for i in 0..vec1.len() {
if vec1[i] != vec2[i] {
return false;
}
}
true
}
}
/// A handy macro for generating OIDs from a sequence of `u64`s.
///
/// Usage: oid!(1,2,840,113549,1,1,1) creates an OID that matches
/// 1.2.840.113549.1.1.1. (Coincidentally, this is RSA.)
#[macro_export]
macro_rules! oid {
( $( $e: expr ),* ) => {{
let mut res = Vec::new();
$(
res.push(BigUint::from($e as u64));
)*
OID::new(res)
}};
}
const PRINTABLE_CHARS: &'static str =
"ABCDEFGHIJKLMOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'()+,-./:=? ";
/// An error that can arise decoding ASN.1 primitive blocks.
#[derive(Clone, Debug, PartialEq)]
pub enum ASN1DecodeErr {
EmptyBuffer,
BadBooleanLength(usize),
LengthTooLarge(usize),
UTF8DecodeFailure(Utf8Error),
PrintableStringDecodeFailure,
InvalidDateValue(String),
InvalidBitStringLength(isize),
/// Not a valid ASN.1 class
InvalidClass(u8),
/// Expected more input
///
/// Invalid ASN.1 input can lead to this error.
Incomplete,
#[doc(hidden)]
__Nonexhaustive,
}
impl fmt::Display for ASN1DecodeErr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ASN1DecodeErr::EmptyBuffer =>
write!(f, "Encountered an empty buffer decoding ASN1 block."),
ASN1DecodeErr::BadBooleanLength(x) =>
write!(f, "Bad length field in boolean block: {}", x),
ASN1DecodeErr::LengthTooLarge(x) =>
write!(f, "Length field too large for object type: {}", x),
ASN1DecodeErr::UTF8DecodeFailure(x) =>
write!(f, "UTF8 string failed to properly decode: {}", x),
ASN1DecodeErr::PrintableStringDecodeFailure =>
write!(f, "Printable string failed to properly decode."),
ASN1DecodeErr::InvalidDateValue(x) =>
write!(f, "Invalid date value: {}", x),
ASN1DecodeErr::InvalidBitStringLength(i) =>
write!(f, "Invalid length of bit string: {}", i),
ASN1DecodeErr::InvalidClass(i) =>
write!(f, "Invalid class value: {}", i),
ASN1DecodeErr::Incomplete =>
write!(f, "Incomplete data or invalid ASN1"),
ASN1DecodeErr::__Nonexhaustive =>
panic!("A non exhaustive error should not be constructed"),
}
}
}
impl Error for ASN1DecodeErr {
fn description(&self) -> &str {
match self {
ASN1DecodeErr::EmptyBuffer =>
"Encountered an empty buffer decoding ASN1 block.",
ASN1DecodeErr::BadBooleanLength(_) =>
"Bad length field in boolean block.",
ASN1DecodeErr::LengthTooLarge(_) =>
"Length field too large for object type.",
ASN1DecodeErr::UTF8DecodeFailure(_) =>
"UTF8 string failed to properly decode.",
ASN1DecodeErr::PrintableStringDecodeFailure =>
"Printable string failed to properly decode.",
ASN1DecodeErr::InvalidDateValue(_) =>
"Invalid date value.",
ASN1DecodeErr::InvalidClass(_) =>
"Invalid class value",
ASN1DecodeErr::InvalidBitStringLength(_) =>
"Invalid length of bit string",
ASN1DecodeErr::Incomplete =>
"Incomplete data or invalid ASN1",
ASN1DecodeErr::__Nonexhaustive =>
panic!("A non exhaustive error should not be constructed"),
}
}
fn cause(&self) -> Option<&dyn Error> {
None
}
fn source(&self) -> Option<&(dyn Error + 'static)> {
None
}
}
/// An error that can arise encoding ASN.1 primitive blocks.
#[derive(Clone, Debug, PartialEq)]
pub enum ASN1EncodeErr {
ObjectIdentHasTooFewFields,
ObjectIdentVal1TooLarge,
ObjectIdentVal2TooLarge,
}
impl fmt::Display for ASN1EncodeErr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.description())
}
}
impl Error for ASN1EncodeErr {
fn description(&self) -> &str {
match self {
ASN1EncodeErr::ObjectIdentHasTooFewFields =>
"ASN1 object identifier has too few fields.",
ASN1EncodeErr::ObjectIdentVal1TooLarge =>
"First value in ASN1 OID is too big.",
ASN1EncodeErr::ObjectIdentVal2TooLarge =>
"Second value in ASN1 OID is too big."
}
}
fn cause(&self) -> Option<&dyn Error> {
None
}
fn source(&self) -> Option<&(dyn Error + 'static)> {
None
}
}
/// Translate a binary blob into a series of `ASN1Block`s, or provide an
/// error if it didn't work.
pub fn from_der(i: &[u8]) -> Result<Vec<ASN1Block>, ASN1DecodeErr> {
from_der_(i, 0)
}
fn from_der_(i: &[u8], start_offset: usize) -> Result<Vec<ASN1Block>, ASN1DecodeErr> {
let mut result: Vec<ASN1Block> = Vec::new();
let mut index: usize = 0;
let len = i.len();
while index < len {
let soff = start_offset + index;
let (tag, constructed, class) = decode_tag(i, &mut index)?;
let len = decode_length(i, &mut index)?;
let checklen = index
.checked_add(len)
.ok_or(ASN1DecodeErr::LengthTooLarge(len))?;
if checklen > i.len() {
return Err(ASN1DecodeErr::Incomplete);
}
let body = &i[index..(index + len)];
if class != ASN1Class::Universal {
if constructed {
// Try to read as explicitly tagged
match from_der_(body, start_offset + index) {
Ok(mut items) => {
if items.len() == 1 {
result.push(ASN1Block::Explicit(
class,
soff,
tag,
Box::new(items.remove(0)),
));
index += len;
continue;
}
}
Err(_) => {}
}
}
result.push(ASN1Block::Unknown(
class,
constructed,
soff,
tag,
body.to_vec(),
));
index += len;
continue;
}
// Universal class
match tag.to_u8() {
// BOOLEAN
Some(0x01) => {
if len != 1 {
return Err(ASN1DecodeErr::BadBooleanLength(len));
}
result.push(ASN1Block::Boolean(soff, body[0] != 0));
}
// INTEGER
Some(0x02) => {
let res = BigInt::from_signed_bytes_be(&body);
result.push(ASN1Block::Integer(soff, res));
}
// BIT STRING
Some(0x03) if body.len() == 0 => {
result.push(ASN1Block::BitString(soff, 0, Vec::new()))
}
Some(0x03) => {
let bits = (&body[1..]).to_vec();
let bitcount = bits.len() * 8;
let rest = body[0] as usize;
if bitcount < rest {
return Err(ASN1DecodeErr::InvalidBitStringLength(
bitcount as isize - rest as isize,
));
}
let nbits = bitcount - (body[0] as usize);
result.push(ASN1Block::BitString(soff, nbits, bits))
}
// OCTET STRING
Some(0x04) => {
result.push(ASN1Block::OctetString(soff, body.to_vec()))
}
// NULL
Some(0x05) => {
result.push(ASN1Block::Null(soff));
}
// OBJECT IDENTIFIER
Some(0x06) => {
let mut value1 = BigUint::zero();
if body.len() == 0 {
return Err(ASN1DecodeErr::Incomplete);
}
let mut value2 = BigUint::from_u8(body[0]).unwrap();
let mut oidres = Vec::new();
let mut bindex = 1;
if body[0] >= 40 {
if body[0] < 80 {
value1 = BigUint::one();
value2 = value2 - BigUint::from_u8(40).unwrap();
} else {
value1 = BigUint::from_u8(2).unwrap();
value2 = value2 - BigUint::from_u8(80).unwrap();
}
}
oidres.push(value1);
oidres.push(value2);
while bindex < body.len() {
oidres.push(decode_base127(body, &mut bindex)?);
}
let res = OID(oidres);
result.push(ASN1Block::ObjectIdentifier(soff, res))
}
// UTF8STRING
Some(0x0C) => {
match String::from_utf8(body.to_vec()) {
Ok(v) =>
result.push(ASN1Block::UTF8String(soff, v)),
Err(e) =>
return Err(ASN1DecodeErr::UTF8DecodeFailure(e.utf8_error()))
}
}
// SEQUENCE
Some(0x10) => {
match from_der_(body, start_offset + index) {
Ok(items) =>
result.push(ASN1Block::Sequence(soff, items)),
Err(e) =>
return Err(e)
}
}
// SET
Some(0x11) => {
match from_der_(body, start_offset + index) {
Ok(items) =>
result.push(ASN1Block::Set(soff, items)),
Err(e) =>
return Err(e)
}
}
// PRINTABLE STRING
Some(0x13) => {
let mut res = String::new();
let val = body.iter().map(|x| *x as char);
for c in val {
if PRINTABLE_CHARS.contains(c) {
res.push(c);
} else {
return Err(ASN1DecodeErr::PrintableStringDecodeFailure);
}
}
result.push(ASN1Block::PrintableString(soff, res));
}
// TELETEX STRINGS
Some(0x14) => {
match String::from_utf8(body.to_vec()) {
Ok(v) =>
result.push(ASN1Block::TeletexString(soff, v)),
Err(e) =>
return Err(ASN1DecodeErr::UTF8DecodeFailure(e.utf8_error()))
}
}
// IA5 (ASCII) STRING
Some(0x16) => {
let val = body.iter().map(|x| *x as char);
let res = String::from_iter(val);
result.push(ASN1Block::IA5String(soff, res))
}
// UTCTime
Some(0x17) => {
if body.len() != 13 {
return Err(ASN1DecodeErr::InvalidDateValue(format!("{}", body.len())));
}
let v = String::from_iter(body.iter().map(|x| *x as char));
match Utc.datetime_from_str(&v, "%y%m%d%H%M%SZ") {
Err(_) =>
return Err(ASN1DecodeErr::InvalidDateValue(v)),
Ok(t) => {
result.push(ASN1Block::UTCTime(soff, t))
}
}
}
// GeneralizedTime
Some(0x18) => {
if body.len() < 15 {
return Err(ASN1DecodeErr::InvalidDateValue(format!("{}", body.len())));
}
let mut v: String = String::from_utf8(body.to_vec())
.map_err(|e| ASN1DecodeErr::UTF8DecodeFailure(e.utf8_error()))?;
// Make sure the string is ascii, otherwise we cannot insert
// chars at specific bytes.
if !v.is_ascii() {
return Err(ASN1DecodeErr::InvalidDateValue(v));
}
// We need to add padding back to the string if it's not there.
if !v.contains('.') {
v.insert(14, '.')
}
while v.len() < 25 {
let idx = v.len() - 1;
v.insert(idx, '0');
}
match Utc.datetime_from_str(&v, "%Y%m%d%H%M%S.%fZ") {
Err(_) =>
return Err(ASN1DecodeErr::InvalidDateValue(v)),
Ok(t) => {
result.push(ASN1Block::GeneralizedTime(soff, t))
}
}
}
// UNIVERSAL STRINGS
Some(0x1C) => {
match String::from_utf8(body.to_vec()) {
Ok(v) =>
result.push(ASN1Block::UniversalString(soff, v)),
Err(e) =>
return Err(ASN1DecodeErr::UTF8DecodeFailure(e.utf8_error()))
}
}
// UNIVERSAL STRINGS
Some(0x1E) => {
match String::from_utf8(body.to_vec()) {
Ok(v) =>
result.push(ASN1Block::BMPString(soff, v)),
Err(e) =>
return Err(ASN1DecodeErr::UTF8DecodeFailure(e.utf8_error()))
}
}
// Dunno.
_ => {
result.push(ASN1Block::Unknown(class, constructed, soff, tag, body.to_vec()));
}
}
index += len;
}
if result.is_empty() {
Err(ASN1DecodeErr::EmptyBuffer)
} else {
Ok(result)
}
}
/// Returns the tag, if the type is constructed and the class.
fn decode_tag(i: &[u8], index: &mut usize) -> Result<(BigUint, bool, ASN1Class), ASN1DecodeErr> {
if *index >= i.len() {
return Err(ASN1DecodeErr::Incomplete);
}
let tagbyte = i[*index];
let constructed = (tagbyte & 0b0010_0000) != 0;
let class = decode_class(tagbyte)?;
let basetag = tagbyte & 0b1_1111;
*index += 1;
if basetag == 0b1_1111 {
let res = decode_base127(i, index)?;
Ok((res, constructed, class))
} else {
Ok((BigUint::from(basetag), constructed, class))
}
}
fn decode_base127(i: &[u8], index: &mut usize) -> Result<BigUint, ASN1DecodeErr> {
let mut res = BigUint::zero();
loop {
if *index >= i.len() {
return Err(ASN1DecodeErr::Incomplete);
}
let nextbyte = i[*index];
*index += 1;
res = (res << 7) + BigUint::from(nextbyte & 0x7f);
if (nextbyte & 0x80) == 0 {
return Ok(res);
}
}
}
fn decode_class(i: u8) -> Result<ASN1Class, ASN1DecodeErr> {
match i >> 6 {
0b00 => Ok(ASN1Class::Universal),
0b01 => Ok(ASN1Class::Application),
0b10 => Ok(ASN1Class::ContextSpecific),
0b11 => Ok(ASN1Class::Private),
_ => Err(ASN1DecodeErr::InvalidClass(i)),
}
}
fn decode_length(i: &[u8], index: &mut usize) -> Result<usize, ASN1DecodeErr> {
if *index >= i.len() {
return Err(ASN1DecodeErr::Incomplete);
}
let startbyte = i[*index];
// NOTE: Technically, this size can be much larger than a usize.
// However, our whole universe starts to break down if we get
// things that big. So we're boring, and only accept lengths
// that fit within a usize.
*index += 1;
if startbyte >= 0x80 {
let mut lenlen = (startbyte & 0x7f) as usize;
let mut res = 0;
if lenlen > size_of::<usize>() {
return Err(ASN1DecodeErr::LengthTooLarge(lenlen));
}
while lenlen > 0 {
if *index >= i.len() {
return Err(ASN1DecodeErr::Incomplete);
}
res = (res << 8) + (i[*index] as usize);
*index += 1;
lenlen -= 1;
}
Ok(res)
} else {
Ok(startbyte as usize)
}
}
/// Given an `ASN1Block`, covert it to its DER encoding, or return an error
/// if something broke along the way.
pub fn to_der(i: &ASN1Block) -> Result<Vec<u8>, ASN1EncodeErr> {
match i {
// BOOLEAN
&ASN1Block::Boolean(_, val) => {
let inttag = BigUint::one();
let mut tagbytes = encode_tag(ASN1Class::Universal, false, &inttag);
tagbytes.push(1);
tagbytes.push(if val { 0xFF } else { 0x00 });
Ok(tagbytes)
}
// INTEGER
&ASN1Block::Integer(_, ref int) => {
let mut base = int.to_signed_bytes_be();
let mut lenbytes = encode_len(base.len());
let inttag = BigUint::from_u8(0x02).unwrap();
let mut tagbytes = encode_tag(ASN1Class::Universal, false, &inttag);
let mut result = Vec::new();
result.append(&mut tagbytes);
result.append(&mut lenbytes);
result.append(&mut base);
Ok(result)
}
// BIT STRING
&ASN1Block::BitString(_, bits, ref vs) => {
let inttag = BigUint::from_u8(0x03).unwrap();
let mut tagbytes = encode_tag(ASN1Class::Universal, false, &inttag);
if bits == 0 {
tagbytes.push(0);
Ok(tagbytes)
} else {
let mut lenbytes = encode_len(vs.len() + 1);
let nbits = (vs.len() * 8) - bits;
let mut result = Vec::new();
result.append(&mut tagbytes);
result.append(&mut lenbytes);
result.push(nbits as u8);
result.extend_from_slice(vs);
Ok(result)
}
}
// OCTET STRING
&ASN1Block::OctetString(_, ref bytes) => {
let inttag = BigUint::from_u8(0x04).unwrap();
let mut tagbytes = encode_tag(ASN1Class::Universal, false, &inttag);
let mut lenbytes = encode_len(bytes.len());
let mut result = Vec::new();
result.append(&mut tagbytes);
result.append(&mut lenbytes);
result.extend_from_slice(bytes);
Ok(result)
}
// NULL
&ASN1Block::Null(_) => {
let inttag = BigUint::from_u8(0x05).unwrap();
let mut result = encode_tag(ASN1Class::Universal, false, &inttag);
result.push(0);
Ok(result)
}
// OBJECT IDENTIFIER
&ASN1Block::ObjectIdentifier(_, OID(ref nums)) => {
match (nums.get(0), nums.get(1)) {
(Some(v1), Some(v2)) => {
let two = BigUint::from_u8(2).unwrap();
// first, validate that the first two items meet spec
if v1 > &two {
return Err(ASN1EncodeErr::ObjectIdentVal1TooLarge)
}
let u175 = BigUint::from_u8(175).unwrap();
let u39 = BigUint::from_u8(39).unwrap();
let bound = if v1 == &two { u175 } else { u39 };
if v2 > &bound {
return Err(ASN1EncodeErr::ObjectIdentVal2TooLarge);
}
// the following unwraps must be safe, based on the
// validation above.
let value1 = v1.to_u8().unwrap();
let value2 = v2.to_u8().unwrap();
let byte1 = (value1 * 40) + value2;
// now we can build all the rest of the body
let mut body = vec![byte1];
for num in nums.iter().skip(2) {
let mut local = encode_base127(&num);
body.append(&mut local);
}
// now that we have the body, we can build the header
let inttag = BigUint::from_u8(0x06).unwrap();
let mut result = encode_tag(ASN1Class::Universal, false, &inttag);
let mut lenbytes = encode_len(body.len());
result.append(&mut lenbytes);
result.append(&mut body);
Ok(result)
}
_ => {
Err(ASN1EncodeErr::ObjectIdentHasTooFewFields)
}
}
}
// SEQUENCE
&ASN1Block::Sequence(_, ref items) => {
let mut body = Vec::new();
// put all the subsequences into a block
for x in items.iter() {
let mut bytes = to_der(x)?;
body.append(&mut bytes);
}
let inttag = BigUint::from_u8(0x10).unwrap();
let mut lenbytes = encode_len(body.len());
// SEQUENCE and SET mut have the constructed encoding form (bit 5) set
// See: https://docs.microsoft.com/en-us/windows/desktop/seccertenroll/about-encoded-tag-bytes
let mut tagbytes = encode_tag(ASN1Class::Universal, true, &inttag);
let mut res = Vec::new();
res.append(&mut tagbytes);
res.append(&mut lenbytes);
res.append(&mut body);
Ok(res)
}
// SET
&ASN1Block::Set(_, ref items) => {
let mut body = Vec::new();
// put all the subsequences into a block
for x in items.iter() {
let mut bytes = to_der(x)?;
body.append(&mut bytes);
}
let inttag = BigUint::from_u8(0x11).unwrap();
let mut lenbytes = encode_len(body.len());
// SEQUENCE and SET mut have the constructed encoding form (bit 5) set
// See: https://docs.microsoft.com/en-us/windows/desktop/seccertenroll/about-encoded-tag-bytes
let mut tagbytes = encode_tag(ASN1Class::Universal, true, &inttag);
let mut res = Vec::new();
res.append(&mut tagbytes);
res.append(&mut lenbytes);
res.append(&mut body);
Ok(res)
}
&ASN1Block::UTCTime(_, ref time) => {
let mut body = time.format("%y%m%d%H%M%SZ").to_string().into_bytes();
let inttag = BigUint::from_u8(0x17).unwrap();
let mut lenbytes = encode_len(body.len());
let mut tagbytes = encode_tag(ASN1Class::Universal, false, &inttag);
let mut res = Vec::new();
res.append(&mut tagbytes);
res.append(&mut lenbytes);
res.append(&mut body);
Ok(res)
}
&ASN1Block::GeneralizedTime(_, ref time) => {
let base = time.format("%Y%m%d%H%M%S.%f").to_string();
let zclear = base.trim_end_matches('0');
let dclear = zclear.trim_end_matches('.');
let mut body = format!("{}Z", dclear).into_bytes();
let inttag = BigUint::from_u8(0x18).unwrap();
let mut lenbytes = encode_len(body.len());
let mut tagbytes = encode_tag(ASN1Class::Universal, false, &inttag);
let mut res = Vec::new();
res.append(&mut tagbytes);
res.append(&mut lenbytes);
res.append(&mut body);
Ok(res)
}
&ASN1Block::UTF8String(_, ref str) =>
encode_asn1_string(0x0c, false, ASN1Class::Universal, str),
&ASN1Block::PrintableString(_, ref str) =>
encode_asn1_string(0x13, true, ASN1Class::Universal, str),
&ASN1Block::TeletexString(_, ref str) =>
encode_asn1_string(0x14, false, ASN1Class::Universal, str),
&ASN1Block::UniversalString(_, ref str) =>
encode_asn1_string(0x1c, false, ASN1Class::Universal, str),
&ASN1Block::IA5String(_, ref str) =>
encode_asn1_string(0x16, true, ASN1Class::Universal, str),
&ASN1Block::BMPString(_, ref str) =>
encode_asn1_string(0x1e, false, ASN1Class::Universal, str),
&ASN1Block::Explicit(class, _, ref tag, ref item) => {
let mut tagbytes = encode_tag(class, true, tag);
let mut bytes = to_der(item)?;
let mut lenbytes = encode_len(bytes.len());
let mut res = Vec::new();
res.append(&mut tagbytes);
res.append(&mut lenbytes);
res.append(&mut bytes);
Ok(res)
}
// Unknown blocks
&ASN1Block::Unknown(class, c, _, ref tag, ref bytes) => {
let mut tagbytes = encode_tag(class, c, tag);
let mut lenbytes = encode_len(bytes.len());
let mut res = Vec::new();
res.append(&mut tagbytes);
res.append(&mut lenbytes);
res.extend_from_slice(bytes);
Ok(res)
}
}
}
fn encode_asn1_string(
tag: u8,
force_chars: bool,
c: ASN1Class,
s: &String,
) -> Result<Vec<u8>, ASN1EncodeErr> {
let mut body = {
if force_chars {
let mut out = Vec::new();
for c in s.chars() {
out.push(c as u8);
}