forked from etingof/pyasn1
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathdecoder.py
More file actions
2225 lines (1654 loc) · 78.9 KB
/
decoder.py
File metadata and controls
2225 lines (1654 loc) · 78.9 KB
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
#
# This file is part of pyasn1 software.
#
# Copyright (c) 2005-2020, Ilya Etingof <[email protected]>
# License: https://pyasn1.readthedocs.io/en/latest/license.html
#
import io
import os
import sys
import warnings
from pyasn1 import debug
from pyasn1 import error
from pyasn1.codec.ber import eoo
from pyasn1.codec.streaming import asSeekableStream
from pyasn1.codec.streaming import isEndOfStream
from pyasn1.codec.streaming import peekIntoStream
from pyasn1.codec.streaming import readFromStream
from pyasn1.compat import _MISSING
from pyasn1.error import PyAsn1Error
from pyasn1.type import base
from pyasn1.type import char
from pyasn1.type import tag
from pyasn1.type import tagmap
from pyasn1.type import univ
from pyasn1.type import useful
__all__ = ['StreamingDecoder', 'Decoder', 'decode']
LOG = debug.registerLoggee(__name__, flags=debug.DEBUG_DECODER)
noValue = base.noValue
SubstrateUnderrunError = error.SubstrateUnderrunError
# Maximum number of continuation octets (high-bit set) allowed per OID arc.
# 20 octets allows up to 140-bit integers, supporting UUID-based OIDs
MAX_OID_ARC_CONTINUATION_OCTETS = 20
MAX_NESTING_DEPTH = 100
# Maximum number of bytes in a BER length field (8 bytes = up to 2^64-1)
MAX_LENGTH_OCTETS = 8
class AbstractPayloadDecoder(object):
protoComponent = None
def valueDecoder(self, substrate, asn1Spec,
tagSet=None, length=None, state=None,
decodeFun=None, substrateFun=None,
**options):
"""Decode value with fixed byte length.
The decoder is allowed to consume as many bytes as necessary.
"""
raise error.PyAsn1Error('SingleItemDecoder not implemented for %s' % (tagSet,)) # TODO: Seems more like an NotImplementedError?
def indefLenValueDecoder(self, substrate, asn1Spec,
tagSet=None, length=None, state=None,
decodeFun=None, substrateFun=None,
**options):
"""Decode value with undefined length.
The decoder is allowed to consume as many bytes as necessary.
"""
raise error.PyAsn1Error('Indefinite length mode decoder not implemented for %s' % (tagSet,)) # TODO: Seems more like an NotImplementedError?
@staticmethod
def _passAsn1Object(asn1Object, options):
if 'asn1Object' not in options:
options['asn1Object'] = asn1Object
return options
class AbstractSimplePayloadDecoder(AbstractPayloadDecoder):
@staticmethod
def substrateCollector(asn1Object, substrate, length, options):
for chunk in readFromStream(substrate, length, options):
yield chunk
def _createComponent(self, asn1Spec, tagSet, value, **options):
if options.get('native'):
return value
elif asn1Spec is None:
return self.protoComponent.clone(value, tagSet=tagSet)
elif value is noValue:
return asn1Spec
else:
return asn1Spec.clone(value)
class RawPayloadDecoder(AbstractSimplePayloadDecoder):
protoComponent = univ.Any('')
def valueDecoder(self, substrate, asn1Spec,
tagSet=None, length=None, state=None,
decodeFun=None, substrateFun=None,
**options):
if substrateFun:
asn1Object = self._createComponent(asn1Spec, tagSet, '', **options)
for chunk in substrateFun(asn1Object, substrate, length, options):
yield chunk
return
for value in decodeFun(substrate, asn1Spec, tagSet, length, **options):
yield value
def indefLenValueDecoder(self, substrate, asn1Spec,
tagSet=None, length=None, state=None,
decodeFun=None, substrateFun=None,
**options):
if substrateFun:
asn1Object = self._createComponent(asn1Spec, tagSet, '', **options)
for chunk in substrateFun(asn1Object, substrate, length, options):
yield chunk
return
while True:
for value in decodeFun(
substrate, asn1Spec, tagSet, length,
allowEoo=True, **options):
if value is eoo.endOfOctets:
return
yield value
rawPayloadDecoder = RawPayloadDecoder()
class IntegerPayloadDecoder(AbstractSimplePayloadDecoder):
protoComponent = univ.Integer(0)
def valueDecoder(self, substrate, asn1Spec,
tagSet=None, length=None, state=None,
decodeFun=None, substrateFun=None,
**options):
if tagSet[0].tagFormat != tag.tagFormatSimple:
raise error.PyAsn1Error('Simple tag format expected')
for chunk in readFromStream(substrate, length, options):
if isinstance(chunk, SubstrateUnderrunError):
yield chunk
if chunk:
value = int.from_bytes(bytes(chunk), 'big', signed=True)
else:
value = 0
yield self._createComponent(asn1Spec, tagSet, value, **options)
class BooleanPayloadDecoder(IntegerPayloadDecoder):
protoComponent = univ.Boolean(0)
def _createComponent(self, asn1Spec, tagSet, value, **options):
return IntegerPayloadDecoder._createComponent(
self, asn1Spec, tagSet, value and 1 or 0, **options)
class BitStringPayloadDecoder(AbstractSimplePayloadDecoder):
protoComponent = univ.BitString(())
supportConstructedForm = True
def valueDecoder(self, substrate, asn1Spec,
tagSet=None, length=None, state=None,
decodeFun=None, substrateFun=None,
**options):
if substrateFun:
asn1Object = self._createComponent(asn1Spec, tagSet, noValue, **options)
for chunk in substrateFun(asn1Object, substrate, length, options):
yield chunk
return
if not length:
raise error.PyAsn1Error('Empty BIT STRING substrate')
for chunk in isEndOfStream(substrate):
if isinstance(chunk, SubstrateUnderrunError):
yield chunk
if chunk:
raise error.PyAsn1Error('Empty BIT STRING substrate')
if tagSet[0].tagFormat == tag.tagFormatSimple: # XXX what tag to check?
for trailingBits in readFromStream(substrate, 1, options):
if isinstance(trailingBits, SubstrateUnderrunError):
yield trailingBits
trailingBits = ord(trailingBits)
if trailingBits > 7:
raise error.PyAsn1Error(
'Trailing bits overflow %s' % trailingBits
)
for chunk in readFromStream(substrate, length - 1, options):
if isinstance(chunk, SubstrateUnderrunError):
yield chunk
value = self.protoComponent.fromOctetString(
chunk, internalFormat=True, padding=trailingBits)
yield self._createComponent(asn1Spec, tagSet, value, **options)
return
if not self.supportConstructedForm:
raise error.PyAsn1Error('Constructed encoding form prohibited '
'at %s' % self.__class__.__name__)
if LOG:
LOG('assembling constructed serialization')
# All inner fragments are of the same type, treat them as octet string
substrateFun = self.substrateCollector
bitString = self.protoComponent.fromOctetString(b'', internalFormat=True)
current_position = substrate.tell()
while substrate.tell() - current_position < length:
for component in decodeFun(
substrate, self.protoComponent, substrateFun=substrateFun,
**options):
if isinstance(component, SubstrateUnderrunError):
yield component
trailingBits = component[0]
if trailingBits > 7:
raise error.PyAsn1Error(
'Trailing bits overflow %s' % trailingBits
)
bitString = self.protoComponent.fromOctetString(
component[1:], internalFormat=True,
prepend=bitString, padding=trailingBits
)
yield self._createComponent(asn1Spec, tagSet, bitString, **options)
def indefLenValueDecoder(self, substrate, asn1Spec,
tagSet=None, length=None, state=None,
decodeFun=None, substrateFun=None,
**options):
if substrateFun:
asn1Object = self._createComponent(asn1Spec, tagSet, noValue, **options)
for chunk in substrateFun(asn1Object, substrate, length, options):
yield chunk
return
# All inner fragments are of the same type, treat them as octet string
substrateFun = self.substrateCollector
bitString = self.protoComponent.fromOctetString(b'', internalFormat=True)
while True: # loop over fragments
for component in decodeFun(
substrate, self.protoComponent, substrateFun=substrateFun,
allowEoo=True, **options):
if component is eoo.endOfOctets:
break
if isinstance(component, SubstrateUnderrunError):
yield component
if component is eoo.endOfOctets:
break
trailingBits = component[0]
if trailingBits > 7:
raise error.PyAsn1Error(
'Trailing bits overflow %s' % trailingBits
)
bitString = self.protoComponent.fromOctetString(
component[1:], internalFormat=True,
prepend=bitString, padding=trailingBits
)
yield self._createComponent(asn1Spec, tagSet, bitString, **options)
class OctetStringPayloadDecoder(AbstractSimplePayloadDecoder):
protoComponent = univ.OctetString('')
supportConstructedForm = True
def valueDecoder(self, substrate, asn1Spec,
tagSet=None, length=None, state=None,
decodeFun=None, substrateFun=None,
**options):
if substrateFun:
asn1Object = self._createComponent(asn1Spec, tagSet, noValue, **options)
for chunk in substrateFun(asn1Object, substrate, length, options):
yield chunk
return
if tagSet[0].tagFormat == tag.tagFormatSimple: # XXX what tag to check?
for chunk in readFromStream(substrate, length, options):
if isinstance(chunk, SubstrateUnderrunError):
yield chunk
yield self._createComponent(asn1Spec, tagSet, chunk, **options)
return
if not self.supportConstructedForm:
raise error.PyAsn1Error('Constructed encoding form prohibited at %s' % self.__class__.__name__)
if LOG:
LOG('assembling constructed serialization')
# All inner fragments are of the same type, treat them as octet string
substrateFun = self.substrateCollector
header = b''
original_position = substrate.tell()
# head = popSubstream(substrate, length)
while substrate.tell() - original_position < length:
for component in decodeFun(
substrate, self.protoComponent, substrateFun=substrateFun,
**options):
if isinstance(component, SubstrateUnderrunError):
yield component
header += component
yield self._createComponent(asn1Spec, tagSet, header, **options)
def indefLenValueDecoder(self, substrate, asn1Spec,
tagSet=None, length=None, state=None,
decodeFun=None, substrateFun=None,
**options):
if substrateFun and substrateFun is not self.substrateCollector:
asn1Object = self._createComponent(asn1Spec, tagSet, noValue, **options)
for chunk in substrateFun(asn1Object, substrate, length, options):
yield chunk
return
# All inner fragments are of the same type, treat them as octet string
substrateFun = self.substrateCollector
header = b''
while True: # loop over fragments
for component in decodeFun(
substrate, self.protoComponent, substrateFun=substrateFun,
allowEoo=True, **options):
if isinstance(component, SubstrateUnderrunError):
yield component
if component is eoo.endOfOctets:
break
if component is eoo.endOfOctets:
break
header += component
yield self._createComponent(asn1Spec, tagSet, header, **options)
class NullPayloadDecoder(AbstractSimplePayloadDecoder):
protoComponent = univ.Null('')
def valueDecoder(self, substrate, asn1Spec,
tagSet=None, length=None, state=None,
decodeFun=None, substrateFun=None,
**options):
if tagSet[0].tagFormat != tag.tagFormatSimple:
raise error.PyAsn1Error('Simple tag format expected')
for chunk in readFromStream(substrate, length, options):
if isinstance(chunk, SubstrateUnderrunError):
yield chunk
component = self._createComponent(asn1Spec, tagSet, '', **options)
if chunk:
raise error.PyAsn1Error('Unexpected %d-octet substrate for Null' % length)
yield component
class ObjectIdentifierPayloadDecoder(AbstractSimplePayloadDecoder):
protoComponent = univ.ObjectIdentifier(())
def valueDecoder(self, substrate, asn1Spec,
tagSet=None, length=None, state=None,
decodeFun=None, substrateFun=None,
**options):
if tagSet[0].tagFormat != tag.tagFormatSimple:
raise error.PyAsn1Error('Simple tag format expected')
for chunk in readFromStream(substrate, length, options):
if isinstance(chunk, SubstrateUnderrunError):
yield chunk
if not chunk:
raise error.PyAsn1Error('Empty substrate')
oid = ()
index = 0
substrateLen = len(chunk)
while index < substrateLen:
subId = chunk[index]
index += 1
if subId < 128:
oid += (subId,)
elif subId > 128:
# Construct subid from a number of octets
nextSubId = subId
subId = 0
continuationOctetCount = 0
while nextSubId >= 128:
continuationOctetCount += 1
if continuationOctetCount > MAX_OID_ARC_CONTINUATION_OCTETS:
raise error.PyAsn1Error(
'OID arc exceeds maximum continuation octets limit (%d) '
'at position %d' % (MAX_OID_ARC_CONTINUATION_OCTETS, index)
)
subId = (subId << 7) + (nextSubId & 0x7F)
if index >= substrateLen:
raise error.SubstrateUnderrunError(
'Short substrate for sub-OID past %s' % (oid,)
)
nextSubId = chunk[index]
index += 1
oid += ((subId << 7) + nextSubId,)
elif subId == 128:
# ASN.1 spec forbids leading zeros (0x80) in OID
# encoding, tolerating it opens a vulnerability. See
# https://www.esat.kuleuven.be/cosic/publications/article-1432.pdf
# page 7
raise error.PyAsn1Error('Invalid octet 0x80 in OID encoding')
# Decode two leading arcs
if 0 <= oid[0] <= 39:
oid = (0,) + oid
elif 40 <= oid[0] <= 79:
oid = (1, oid[0] - 40) + oid[1:]
elif oid[0] >= 80:
oid = (2, oid[0] - 80) + oid[1:]
else:
raise error.PyAsn1Error('Malformed first OID octet: %s' % chunk[0])
yield self._createComponent(asn1Spec, tagSet, oid, **options)
class RelativeOIDPayloadDecoder(AbstractSimplePayloadDecoder):
protoComponent = univ.RelativeOID(())
def valueDecoder(self, substrate, asn1Spec,
tagSet=None, length=None, state=None,
decodeFun=None, substrateFun=None,
**options):
if tagSet[0].tagFormat != tag.tagFormatSimple:
raise error.PyAsn1Error('Simple tag format expected')
for chunk in readFromStream(substrate, length, options):
if isinstance(chunk, SubstrateUnderrunError):
yield chunk
if not chunk:
raise error.PyAsn1Error('Empty substrate')
reloid = ()
index = 0
substrateLen = len(chunk)
while index < substrateLen:
subId = chunk[index]
index += 1
if subId < 128:
reloid += (subId,)
elif subId > 128:
# Construct subid from a number of octets
nextSubId = subId
subId = 0
continuationOctetCount = 0
while nextSubId >= 128:
continuationOctetCount += 1
if continuationOctetCount > MAX_OID_ARC_CONTINUATION_OCTETS:
raise error.PyAsn1Error(
'RELATIVE-OID arc exceeds maximum continuation octets limit (%d) '
'at position %d' % (MAX_OID_ARC_CONTINUATION_OCTETS, index)
)
subId = (subId << 7) + (nextSubId & 0x7F)
if index >= substrateLen:
raise error.SubstrateUnderrunError(
'Short substrate for sub-OID past %s' % (reloid,)
)
nextSubId = chunk[index]
index += 1
reloid += ((subId << 7) + nextSubId,)
elif subId == 128:
# ASN.1 spec forbids leading zeros (0x80) in OID
# encoding, tolerating it opens a vulnerability. See
# https://www.esat.kuleuven.be/cosic/publications/article-1432.pdf
# page 7
raise error.PyAsn1Error('Invalid octet 0x80 in RELATIVE-OID encoding')
yield self._createComponent(asn1Spec, tagSet, reloid, **options)
class RealPayloadDecoder(AbstractSimplePayloadDecoder):
protoComponent = univ.Real()
def valueDecoder(self, substrate, asn1Spec,
tagSet=None, length=None, state=None,
decodeFun=None, substrateFun=None,
**options):
if tagSet[0].tagFormat != tag.tagFormatSimple:
raise error.PyAsn1Error('Simple tag format expected')
for chunk in readFromStream(substrate, length, options):
if isinstance(chunk, SubstrateUnderrunError):
yield chunk
if not chunk:
yield self._createComponent(asn1Spec, tagSet, 0.0, **options)
return
fo = chunk[0]
chunk = chunk[1:]
if fo & 0x80: # binary encoding
if not chunk:
raise error.PyAsn1Error("Incomplete floating-point value")
if LOG:
LOG('decoding binary encoded REAL')
n = (fo & 0x03) + 1
if n == 4:
n = chunk[0]
chunk = chunk[1:]
eo, chunk = chunk[:n], chunk[n:]
if not eo or not chunk:
raise error.PyAsn1Error('Real exponent screwed')
e = eo[0] & 0x80 and -1 or 0
while eo: # exponent
e <<= 8
e |= eo[0]
eo = eo[1:]
b = fo >> 4 & 0x03 # base bits
if b > 2:
raise error.PyAsn1Error('Illegal Real base')
if b == 1: # encbase = 8
e *= 3
elif b == 2: # encbase = 16
e *= 4
p = 0
while chunk: # value
p <<= 8
p |= chunk[0]
chunk = chunk[1:]
if fo & 0x40: # sign bit
p = -p
sf = fo >> 2 & 0x03 # scale bits
p *= 2 ** sf
value = (p, 2, e)
elif fo & 0x40: # infinite value
if LOG:
LOG('decoding infinite REAL')
value = fo & 0x01 and '-inf' or 'inf'
elif fo & 0xc0 == 0: # character encoding
if not chunk:
raise error.PyAsn1Error("Incomplete floating-point value")
if LOG:
LOG('decoding character encoded REAL')
try:
if fo & 0x3 == 0x1: # NR1
value = (int(chunk), 10, 0)
elif fo & 0x3 == 0x2: # NR2
value = float(chunk)
elif fo & 0x3 == 0x3: # NR3
value = float(chunk)
else:
raise error.SubstrateUnderrunError(
'Unknown NR (tag %s)' % fo
)
except ValueError:
raise error.SubstrateUnderrunError(
'Bad character Real syntax'
)
else:
raise error.SubstrateUnderrunError(
'Unknown encoding (tag %s)' % fo
)
yield self._createComponent(asn1Spec, tagSet, value, **options)
class AbstractConstructedPayloadDecoder(AbstractPayloadDecoder):
protoComponent = None
class ConstructedPayloadDecoderBase(AbstractConstructedPayloadDecoder):
protoRecordComponent = None
protoSequenceComponent = None
def _getComponentTagMap(self, asn1Object, idx):
raise NotImplementedError
def _getComponentPositionByType(self, asn1Object, tagSet, idx):
raise NotImplementedError
def _decodeComponentsSchemaless(
self, substrate, tagSet=None, decodeFun=None,
length=None, **options):
asn1Object = None
components = []
componentTypes = set()
original_position = substrate.tell()
while length == -1 or substrate.tell() < original_position + length:
for component in decodeFun(substrate, **options):
if isinstance(component, SubstrateUnderrunError):
yield component
if length == -1 and component is eoo.endOfOctets:
break
components.append(component)
componentTypes.add(component.tagSet)
# Now we have to guess is it SEQUENCE/SET or SEQUENCE OF/SET OF
# The heuristics is:
# * 1+ components of different types -> likely SEQUENCE/SET
# * otherwise -> likely SEQUENCE OF/SET OF
if len(componentTypes) > 1:
protoComponent = self.protoRecordComponent
else:
protoComponent = self.protoSequenceComponent
asn1Object = protoComponent.clone(
# construct tagSet from base tag from prototype ASN.1 object
# and additional tags recovered from the substrate
tagSet=tag.TagSet(protoComponent.tagSet.baseTag, *tagSet.superTags)
)
if LOG:
LOG('guessed %r container type (pass `asn1Spec` to guide the '
'decoder)' % asn1Object)
for idx, component in enumerate(components):
asn1Object.setComponentByPosition(
idx, component,
verifyConstraints=False,
matchTags=False, matchConstraints=False
)
yield asn1Object
def valueDecoder(self, substrate, asn1Spec,
tagSet=None, length=None, state=None,
decodeFun=None, substrateFun=None,
**options):
if tagSet[0].tagFormat != tag.tagFormatConstructed:
raise error.PyAsn1Error('Constructed tag format expected')
original_position = substrate.tell()
if substrateFun:
if asn1Spec is not None:
asn1Object = asn1Spec.clone()
elif self.protoComponent is not None:
asn1Object = self.protoComponent.clone(tagSet=tagSet)
else:
asn1Object = self.protoRecordComponent, self.protoSequenceComponent
for chunk in substrateFun(asn1Object, substrate, length, options):
yield chunk
return
if asn1Spec is None:
for asn1Object in self._decodeComponentsSchemaless(
substrate, tagSet=tagSet, decodeFun=decodeFun,
length=length, **options):
if isinstance(asn1Object, SubstrateUnderrunError):
yield asn1Object
if substrate.tell() < original_position + length:
if LOG:
for trailing in readFromStream(substrate, context=options):
if isinstance(trailing, SubstrateUnderrunError):
yield trailing
LOG('Unused trailing %d octets encountered: %s' % (
len(trailing), debug.hexdump(trailing)))
yield asn1Object
return
asn1Object = asn1Spec.clone()
asn1Object.clear()
options = self._passAsn1Object(asn1Object, options)
if asn1Spec.typeId in (univ.Sequence.typeId, univ.Set.typeId):
namedTypes = asn1Spec.componentType
isSetType = asn1Spec.typeId == univ.Set.typeId
isDeterministic = not isSetType and not namedTypes.hasOptionalOrDefault
if LOG:
LOG('decoding %sdeterministic %s type %r chosen by type ID' % (
not isDeterministic and 'non-' or '', isSetType and 'SET' or '',
asn1Spec))
seenIndices = set()
idx = 0
while substrate.tell() - original_position < length:
if not namedTypes:
componentType = None
elif isSetType:
componentType = namedTypes.tagMapUnique
else:
try:
if isDeterministic:
componentType = namedTypes[idx].asn1Object
elif namedTypes[idx].isOptional or namedTypes[idx].isDefaulted:
componentType = namedTypes.getTagMapNearPosition(idx)
else:
componentType = namedTypes[idx].asn1Object
except IndexError:
raise error.PyAsn1Error(
'Excessive components decoded at %r' % (asn1Spec,)
)
for component in decodeFun(substrate, componentType, **options):
if isinstance(component, SubstrateUnderrunError):
yield component
if not isDeterministic and namedTypes:
if isSetType:
idx = namedTypes.getPositionByType(component.effectiveTagSet)
elif namedTypes[idx].isOptional or namedTypes[idx].isDefaulted:
idx = namedTypes.getPositionNearType(component.effectiveTagSet, idx)
asn1Object.setComponentByPosition(
idx, component,
verifyConstraints=False,
matchTags=False, matchConstraints=False
)
seenIndices.add(idx)
idx += 1
if LOG:
LOG('seen component indices %s' % seenIndices)
if namedTypes:
if not namedTypes.requiredComponents.issubset(seenIndices):
raise error.PyAsn1Error(
'ASN.1 object %s has uninitialized '
'components' % asn1Object.__class__.__name__)
if namedTypes.hasOpenTypes:
openTypes = options.get('openTypes', {})
if LOG:
LOG('user-specified open types map:')
for k, v in openTypes.items():
LOG('%s -> %r' % (k, v))
if openTypes or options.get('decodeOpenTypes', False):
for idx, namedType in enumerate(namedTypes.namedTypes):
if not namedType.openType:
continue
if namedType.isOptional and not asn1Object.getComponentByPosition(idx).isValue:
continue
governingValue = asn1Object.getComponentByName(
namedType.openType.name
)
try:
openType = openTypes[governingValue]
except KeyError:
if LOG:
LOG('default open types map of component '
'"%s.%s" governed by component "%s.%s"'
':' % (asn1Object.__class__.__name__,
namedType.name,
asn1Object.__class__.__name__,
namedType.openType.name))
for k, v in namedType.openType.items():
LOG('%s -> %r' % (k, v))
try:
openType = namedType.openType[governingValue]
except KeyError:
if LOG:
LOG('failed to resolve open type by governing '
'value %r' % (governingValue,))
continue
if LOG:
LOG('resolved open type %r by governing '
'value %r' % (openType, governingValue))
containerValue = asn1Object.getComponentByPosition(idx)
if containerValue.typeId in (
univ.SetOf.typeId, univ.SequenceOf.typeId):
for pos, containerElement in enumerate(
containerValue):
stream = asSeekableStream(containerValue[pos].asOctets())
for component in decodeFun(stream, asn1Spec=openType, **options):
if isinstance(component, SubstrateUnderrunError):
yield component
containerValue[pos] = component
else:
stream = asSeekableStream(asn1Object.getComponentByPosition(idx).asOctets())
for component in decodeFun(stream, asn1Spec=openType, **options):
if isinstance(component, SubstrateUnderrunError):
yield component
asn1Object.setComponentByPosition(idx, component)
else:
inconsistency = asn1Object.isInconsistent
if inconsistency:
raise error.PyAsn1Error(
f"ASN.1 object {asn1Object.__class__.__name__} is inconsistent")
else:
componentType = asn1Spec.componentType
if LOG:
LOG('decoding type %r chosen by given `asn1Spec`' % componentType)
idx = 0
while substrate.tell() - original_position < length:
for component in decodeFun(substrate, componentType, **options):
if isinstance(component, SubstrateUnderrunError):
yield component
asn1Object.setComponentByPosition(
idx, component,
verifyConstraints=False,
matchTags=False, matchConstraints=False
)
idx += 1
yield asn1Object
def indefLenValueDecoder(self, substrate, asn1Spec,
tagSet=None, length=None, state=None,
decodeFun=None, substrateFun=None,
**options):
if tagSet[0].tagFormat != tag.tagFormatConstructed:
raise error.PyAsn1Error('Constructed tag format expected')
if substrateFun is not None:
if asn1Spec is not None:
asn1Object = asn1Spec.clone()
elif self.protoComponent is not None:
asn1Object = self.protoComponent.clone(tagSet=tagSet)
else:
asn1Object = self.protoRecordComponent, self.protoSequenceComponent
for chunk in substrateFun(asn1Object, substrate, length, options):
yield chunk
return
if asn1Spec is None:
for asn1Object in self._decodeComponentsSchemaless(
substrate, tagSet=tagSet, decodeFun=decodeFun,
length=length, **dict(options, allowEoo=True)):
if isinstance(asn1Object, SubstrateUnderrunError):
yield asn1Object
yield asn1Object
return
asn1Object = asn1Spec.clone()
asn1Object.clear()
options = self._passAsn1Object(asn1Object, options)
if asn1Spec.typeId in (univ.Sequence.typeId, univ.Set.typeId):
namedTypes = asn1Object.componentType
isSetType = asn1Object.typeId == univ.Set.typeId
isDeterministic = not isSetType and not namedTypes.hasOptionalOrDefault
if LOG:
LOG('decoding %sdeterministic %s type %r chosen by type ID' % (
not isDeterministic and 'non-' or '', isSetType and 'SET' or '',
asn1Spec))
seenIndices = set()
idx = 0
while True: # loop over components
if len(namedTypes) <= idx:
asn1Spec = None
elif isSetType:
asn1Spec = namedTypes.tagMapUnique
else:
try:
if isDeterministic:
asn1Spec = namedTypes[idx].asn1Object
elif namedTypes[idx].isOptional or namedTypes[idx].isDefaulted:
asn1Spec = namedTypes.getTagMapNearPosition(idx)
else:
asn1Spec = namedTypes[idx].asn1Object
except IndexError:
raise error.PyAsn1Error(
'Excessive components decoded at %r' % (asn1Object,)
)