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
use crate::ber::*;
use crate::der_constraint_fail_if;
use crate::error::*;
use crate::DynTagged;
use crate::ToDer;
use crate::ToStatic;
use crate::{FromBer, FromDer};
use nom::bytes::streaming::take;
use rusticata_macros::newtype_enum;
use std::borrow::Cow;
use std::convert::TryFrom;
use std::fmt;
use std::ops;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct BerClassFromIntError(pub(crate) ());
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[repr(u8)]
pub enum Class {
Universal = 0b00,
Application = 0b01,
ContextSpecific = 0b10,
Private = 0b11,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Tag(pub u32);
newtype_enum! {
impl display Tag {
EndOfContent = 0x0,
Boolean = 0x1,
Integer = 0x2,
BitString = 0x3,
OctetString = 0x4,
Null = 0x05,
Oid = 0x06,
ObjDescriptor = 0x07,
External = 0x08,
RealType = 0x09,
Enumerated = 0xa,
EmbeddedPdv = 0xb,
Utf8String = 0xc,
RelativeOid = 0xd,
Sequence = 0x10,
Set = 0x11,
NumericString = 0x12,
PrintableString = 0x13,
T61String = 0x14,
TeletexString = 0x14,
VideotexString = 0x15,
Ia5String = 0x16,
UtcTime = 0x17,
GeneralizedTime = 0x18,
GraphicString = 25,
VisibleString = 26,
GeneralString = 27,
UniversalString = 0x1c,
BmpString = 0x1e,
Invalid = 0xff,
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Length {
Definite(usize),
Indefinite,
}
#[derive(Clone, Debug)]
pub struct Header<'a> {
pub(crate) class: Class,
pub(crate) constructed: bool,
pub(crate) tag: Tag,
pub(crate) length: Length,
pub(crate) raw_tag: Option<Cow<'a, [u8]>>,
}
impl fmt::Display for Class {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Class::Universal => "UNIVERSAL",
Class::Application => "APPLICATION",
Class::ContextSpecific => "CONTEXT-SPECIFIC",
Class::Private => "PRIVATE",
};
write!(f, "{}", s)
}
}
impl TryFrom<u8> for Class {
type Error = BerClassFromIntError;
#[inline]
fn try_from(value: u8) -> std::result::Result<Self, Self::Error> {
match value {
0b00 => Ok(Class::Universal),
0b01 => Ok(Class::Application),
0b10 => Ok(Class::ContextSpecific),
0b11 => Ok(Class::Private),
_ => Err(BerClassFromIntError(())),
}
}
}
impl Tag {
pub const fn assert_eq(&self, tag: Tag) -> Result<()> {
if self.0 == tag.0 {
Ok(())
} else {
Err(Error::UnexpectedTag {
expected: Some(tag),
actual: *self,
})
}
}
pub fn invalid_value(&self, msg: &str) -> Error {
Error::InvalidValue {
tag: *self,
msg: msg.to_string(),
}
}
}
impl From<u32> for Tag {
fn from(v: u32) -> Self {
Tag(v)
}
}
impl Length {
#[inline]
pub fn is_null(&self) -> bool {
*self == Length::Definite(0)
}
#[inline]
pub fn definite(&self) -> Result<usize> {
match self {
Length::Definite(sz) => Ok(*sz),
Length::Indefinite => Err(Error::IndefiniteLengthUnexpected),
}
}
#[inline]
pub const fn is_definite(&self) -> bool {
matches!(self, Length::Definite(_))
}
#[inline]
pub const fn assert_definite(&self) -> Result<()> {
match self {
Length::Definite(_) => Ok(()),
Length::Indefinite => Err(Error::IndefiniteLengthUnexpected),
}
}
}
impl From<usize> for Length {
fn from(l: usize) -> Self {
Length::Definite(l)
}
}
impl ops::Add<Length> for Length {
type Output = Self;
fn add(self, rhs: Length) -> Self::Output {
match self {
Length::Indefinite => self,
Length::Definite(lhs) => match rhs {
Length::Indefinite => self,
Length::Definite(rhs) => Length::Definite(lhs + rhs),
},
}
}
}
impl ops::Add<usize> for Length {
type Output = Self;
fn add(self, rhs: usize) -> Self::Output {
match self {
Length::Definite(lhs) => Length::Definite(lhs + rhs),
Length::Indefinite => self,
}
}
}
impl ops::AddAssign<usize> for Length {
fn add_assign(&mut self, rhs: usize) {
match self {
Length::Definite(ref mut lhs) => *lhs += rhs,
Length::Indefinite => (),
}
}
}
impl<'a> Header<'a> {
pub const fn new(class: Class, constructed: bool, tag: Tag, length: Length) -> Self {
Header {
tag,
constructed,
class,
length,
raw_tag: None,
}
}
#[inline]
pub const fn new_simple(tag: Tag) -> Self {
let constructed = matches!(tag, Tag::Sequence | Tag::Set);
Self::new(Class::Universal, constructed, tag, Length::Definite(0))
}
#[inline]
pub fn with_class(self, class: Class) -> Self {
Self { class, ..self }
}
#[inline]
pub fn with_constructed(self, constructed: bool) -> Self {
Self {
constructed,
..self
}
}
#[inline]
pub fn with_tag(self, tag: Tag) -> Self {
Self { tag, ..self }
}
#[inline]
pub fn with_lenth(self, length: Length) -> Self {
Self { length, ..self }
}
#[inline]
pub fn with_raw_tag(self, raw_tag: Option<Cow<'a, [u8]>>) -> Self {
Header { raw_tag, ..self }
}
#[inline]
pub const fn class(&self) -> Class {
self.class
}
#[inline]
pub const fn constructed(&self) -> bool {
self.constructed
}
#[inline]
pub const fn tag(&self) -> Tag {
self.tag
}
#[inline]
pub const fn length(&self) -> Length {
self.length
}
#[inline]
pub const fn is_primitive(&self) -> bool {
!self.constructed
}
#[inline]
pub const fn is_constructed(&self) -> bool {
self.constructed
}
#[inline]
pub const fn assert_class(&self, class: Class) -> Result<()> {
if self.class as u8 == class as u8 {
Ok(())
} else {
Err(Error::UnexpectedClass(class))
}
}
#[inline]
pub const fn assert_tag(&self, tag: Tag) -> Result<()> {
self.tag.assert_eq(tag)
}
#[inline]
pub const fn assert_primitive(&self) -> Result<()> {
if self.is_primitive() {
Ok(())
} else {
Err(Error::ConstructUnexpected)
}
}
#[inline]
pub const fn assert_constructed(&self) -> Result<()> {
if !self.is_primitive() {
Ok(())
} else {
Err(Error::ConstructExpected)
}
}
}
impl<'a> ToStatic for Header<'a> {
type Owned = Header<'static>;
fn to_static(&self) -> Self::Owned {
let raw_tag: Option<Cow<'static, [u8]>> =
self.raw_tag.as_ref().map(|b| Cow::Owned(b.to_vec()));
Header {
tag: self.tag,
constructed: self.constructed,
class: self.class,
length: self.length,
raw_tag,
}
}
}
impl<'a> FromBer<'a> for Header<'a> {
fn from_ber(bytes: &'a [u8]) -> ParseResult<Self> {
let (i1, el) = parse_identifier(bytes)?;
let class = match Class::try_from(el.0) {
Ok(c) => c,
Err(_) => unreachable!(),
};
let (i2, len) = parse_ber_length_byte(i1)?;
let (i3, len) = match (len.0, len.1) {
(0, l1) => {
(i2, Length::Definite(usize::from(l1)))
}
(_, 0) => {
if el.1 == 0 {
return Err(nom::Err::Error(Error::ConstructExpected));
}
(i2, Length::Indefinite)
}
(_, l1) => {
if l1 == 0b0111_1111 {
return Err(::nom::Err::Error(Error::InvalidLength));
}
let (i3, llen) = take(l1)(i2)?;
match bytes_to_u64(llen) {
Ok(l) => {
let l =
usize::try_from(l).or(Err(::nom::Err::Error(Error::InvalidLength)))?;
(i3, Length::Definite(l))
}
Err(_) => {
return Err(::nom::Err::Error(Error::InvalidLength));
}
}
}
};
let constructed = el.1 != 0;
let hdr = Header::new(class, constructed, Tag(el.2), len).with_raw_tag(Some(el.3.into()));
Ok((i3, hdr))
}
}
impl<'a> FromDer<'a> for Header<'a> {
fn from_der(bytes: &'a [u8]) -> ParseResult<Self> {
let (i1, el) = parse_identifier(bytes)?;
let class = match Class::try_from(el.0) {
Ok(c) => c,
Err(_) => unreachable!(),
};
let (i2, len) = parse_ber_length_byte(i1)?;
let (i3, len) = match (len.0, len.1) {
(0, l1) => {
(i2, Length::Definite(usize::from(l1)))
}
(_, 0) => {
return Err(::nom::Err::Error(Error::IndefiniteLengthUnexpected));
}
(_, l1) => {
if l1 == 0b0111_1111 {
return Err(::nom::Err::Error(Error::InvalidLength));
}
der_constraint_fail_if!(&i[1..], len.1 == 0 && el.1 != 1);
let (i3, llen) = take(l1)(i2)?;
match bytes_to_u64(llen) {
Ok(l) => {
let l =
usize::try_from(l).or(Err(::nom::Err::Error(Error::InvalidLength)))?;
(i3, Length::Definite(l))
}
Err(_) => {
return Err(::nom::Err::Error(Error::InvalidLength));
}
}
}
};
let constructed = el.1 != 0;
let hdr = Header::new(class, constructed, Tag(el.2), len).with_raw_tag(Some(el.3.into()));
Ok((i3, hdr))
}
}
impl DynTagged for (Class, bool, Tag) {
fn tag(&self) -> Tag {
self.2
}
}
impl ToDer for (Class, bool, Tag) {
fn to_der_len(&self) -> Result<usize> {
let (_, _, tag) = self;
match tag.0 {
0..=30 => Ok(1),
t => {
let mut sz = 1;
let mut val = t;
loop {
if val <= 127 {
return Ok(sz + 1);
} else {
val >>= 7;
sz += 1;
}
}
}
}
}
fn write_der_header(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
let (class, constructed, tag) = self;
let b0 = (*class as u8) << 6;
let b0 = b0 | if *constructed { 0b10_0000 } else { 0 };
if tag.0 > 30 {
let b0 = b0 | 0b1_1111;
let mut sz = writer.write(&[b0])?;
let mut val = tag.0;
loop {
if val <= 127 {
sz += writer.write(&[val as u8])?;
return Ok(sz);
} else {
let b = (val & 0b0111_1111) as u8 | 0b1000_0000;
sz += writer.write(&[b])?;
val >>= 7;
}
}
} else {
let b0 = b0 | (tag.0 as u8);
let sz = writer.write(&[b0])?;
Ok(sz)
}
}
fn write_der_content(&self, _writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
Ok(0)
}
}
impl DynTagged for Length {
fn tag(&self) -> Tag {
Tag(0)
}
}
impl ToDer for Length {
fn to_der_len(&self) -> Result<usize> {
match self {
Length::Indefinite => Ok(1),
Length::Definite(l) => match l {
0..=0x7f => Ok(1),
0x80..=0xff => Ok(2),
0x100..=0x7fff => Ok(3),
0x8000..=0xffff => Ok(4),
_ => Err(Error::InvalidLength),
},
}
}
fn write_der_header(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
match *self {
Length::Indefinite => {
let sz = writer.write(&[0b1000_0000])?;
Ok(sz)
}
Length::Definite(l) => {
if l <= 127 {
let sz = writer.write(&[l as u8])?;
Ok(sz)
} else {
let mut sz = 0;
let mut val = l;
loop {
if val <= 127 {
sz += writer.write(&[val as u8])?;
return Ok(sz);
} else {
let b = (val & 0b0111_1111) as u8 | 0b1000_0000;
sz += writer.write(&[b])?;
val >>= 7;
}
}
}
}
}
}
fn write_der_content(&self, _writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
Ok(0)
}
}
impl DynTagged for Header<'_> {
fn tag(&self) -> Tag {
self.tag
}
}
impl ToDer for Header<'_> {
fn to_der_len(&self) -> Result<usize> {
let tag_len = (self.class, self.constructed, self.tag).to_der_len()?;
let len_len = self.length.to_der_len()?;
Ok(tag_len + len_len)
}
fn write_der_header(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
let sz = (self.class, self.constructed, self.tag).write_der_header(writer)?;
let sz = sz + self.length.write_der_header(writer)?;
Ok(sz)
}
fn write_der_content(&self, _writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
Ok(0)
}
fn write_der_raw(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
let sz = match &self.raw_tag {
Some(t) => writer.write(&t)?,
None => (self.class, self.constructed, self.tag).write_der_header(writer)?,
};
let sz = sz + self.length.write_der_header(writer)?;
Ok(sz)
}
}
impl<'a> PartialEq<Header<'a>> for Header<'a> {
fn eq(&self, other: &Header) -> bool {
self.class == other.class
&& self.tag == other.tag
&& self.constructed == other.constructed
&& {
if self.length.is_null() && other.length.is_null() {
self.length == other.length
} else {
true
}
}
&& {
if self.raw_tag.as_ref().xor(other.raw_tag.as_ref()).is_none() {
self.raw_tag == other.raw_tag
} else {
true
}
}
}
}
impl Eq for Header<'_> {}