Skip to content

Commit 5a49bd1

Browse files
committed
Merge commit from fork
1 parent 5494ba4 commit 5a49bd1

4 files changed

Lines changed: 192 additions & 0 deletions

File tree

‎pyasn1/codec/ber/decoder.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
# Maximum number of continuation octets (high-bit set) allowed per OID arc.
3737
# 20 octets allows up to 140-bit integers, supporting UUID-based OIDs
3838
MAX_OID_ARC_CONTINUATION_OCTETS = 20
39+
MAX_NESTING_DEPTH = 100
3940

4041
# Maximum number of bytes in a BER length field (8 bytes = up to 2^64-1)
4142
MAX_LENGTH_OCTETS = 8
@@ -1568,6 +1569,15 @@ def __call__(self, substrate, asn1Spec=None,
15681569
decodeFun=None, substrateFun=None,
15691570
**options):
15701571

1572+
_nestingLevel = options.get('_nestingLevel', 0)
1573+
1574+
if _nestingLevel > MAX_NESTING_DEPTH:
1575+
raise error.PyAsn1Error(
1576+
'ASN.1 structure nesting depth exceeds limit (%d)' % MAX_NESTING_DEPTH
1577+
)
1578+
1579+
options['_nestingLevel'] = _nestingLevel + 1
1580+
15711581
allowEoo = options.pop('allowEoo', False)
15721582

15731583
if LOG:

‎tests/codec/ber/test_decoder.py‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2172,6 +2172,122 @@ def testErrorMessageContainsLimit(self):
21722172
assert False, 'Expected PyAsn1Error'
21732173

21742174

2175+
class NestingDepthLimitTestCase(BaseTestCase):
2176+
"""Test protection against deeply nested ASN.1 structures (CVE prevention)."""
2177+
2178+
def testIndefLenSequenceNesting(self):
2179+
"""Deeply nested indefinite-length SEQUENCEs must raise PyAsn1Error."""
2180+
# Each \x30\x80 opens a new indefinite-length SEQUENCE
2181+
payload = b'\x30\x80' * 200
2182+
try:
2183+
decoder.decode(payload)
2184+
except error.PyAsn1Error:
2185+
pass
2186+
else:
2187+
assert False, 'Deeply nested indef-length SEQUENCEs not rejected'
2188+
2189+
def testIndefLenSetNesting(self):
2190+
"""Deeply nested indefinite-length SETs must raise PyAsn1Error."""
2191+
# Each \x31\x80 opens a new indefinite-length SET
2192+
payload = b'\x31\x80' * 200
2193+
try:
2194+
decoder.decode(payload)
2195+
except error.PyAsn1Error:
2196+
pass
2197+
else:
2198+
assert False, 'Deeply nested indef-length SETs not rejected'
2199+
2200+
def testDefiniteLenNesting(self):
2201+
"""Deeply nested definite-length SEQUENCEs must raise PyAsn1Error."""
2202+
inner = b'\x05\x00' # NULL
2203+
for _ in range(200):
2204+
length = len(inner)
2205+
if length < 128:
2206+
inner = b'\x30' + bytes([length]) + inner
2207+
else:
2208+
length_bytes = length.to_bytes(
2209+
(length.bit_length() + 7) // 8, 'big')
2210+
inner = b'\x30' + bytes([0x80 | len(length_bytes)]) + \
2211+
length_bytes + inner
2212+
try:
2213+
decoder.decode(inner)
2214+
except error.PyAsn1Error:
2215+
pass
2216+
else:
2217+
assert False, 'Deeply nested definite-length SEQUENCEs not rejected'
2218+
2219+
def testNestingUnderLimitWorks(self):
2220+
"""Nesting within the limit must decode successfully."""
2221+
inner = b'\x05\x00' # NULL
2222+
for _ in range(50):
2223+
length = len(inner)
2224+
if length < 128:
2225+
inner = b'\x30' + bytes([length]) + inner
2226+
else:
2227+
length_bytes = length.to_bytes(
2228+
(length.bit_length() + 7) // 8, 'big')
2229+
inner = b'\x30' + bytes([0x80 | len(length_bytes)]) + \
2230+
length_bytes + inner
2231+
asn1Object, _ = decoder.decode(inner)
2232+
assert asn1Object is not None, 'Valid nested structure rejected'
2233+
2234+
def testSiblingsDontIncreaseDepth(self):
2235+
"""Sibling elements at the same level must not inflate depth count."""
2236+
# SEQUENCE containing 200 INTEGER siblings - should decode fine
2237+
components = b'\x02\x01\x01' * 200 # 200 x INTEGER(1)
2238+
length = len(components)
2239+
length_bytes = length.to_bytes(
2240+
(length.bit_length() + 7) // 8, 'big')
2241+
payload = b'\x30' + bytes([0x80 | len(length_bytes)]) + \
2242+
length_bytes + components
2243+
asn1Object, _ = decoder.decode(payload)
2244+
assert asn1Object is not None, 'Siblings incorrectly rejected'
2245+
2246+
def testErrorMessageContainsLimit(self):
2247+
"""Error message must indicate the nesting depth limit."""
2248+
payload = b'\x30\x80' * 200
2249+
try:
2250+
decoder.decode(payload)
2251+
except error.PyAsn1Error as exc:
2252+
assert 'nesting depth' in str(exc).lower(), \
2253+
'Error message missing depth info: %s' % exc
2254+
else:
2255+
assert False, 'Expected PyAsn1Error'
2256+
2257+
def testNoRecursionError(self):
2258+
"""Must raise PyAsn1Error, not RecursionError."""
2259+
payload = b'\x30\x80' * 50000
2260+
try:
2261+
decoder.decode(payload)
2262+
except error.PyAsn1Error:
2263+
pass
2264+
except RecursionError:
2265+
assert False, 'Got RecursionError instead of PyAsn1Error'
2266+
2267+
def testMixedNesting(self):
2268+
"""Mixed SEQUENCE and SET nesting must be caught."""
2269+
# Alternate SEQUENCE (0x30) and SET (0x31) with indef length
2270+
payload = b''
2271+
for i in range(200):
2272+
payload += b'\x30\x80' if i % 2 == 0 else b'\x31\x80'
2273+
try:
2274+
decoder.decode(payload)
2275+
except error.PyAsn1Error:
2276+
pass
2277+
else:
2278+
assert False, 'Mixed nesting not rejected'
2279+
2280+
def testWithSchema(self):
2281+
"""Deeply nested structures must be caught even with schema."""
2282+
payload = b'\x30\x80' * 200
2283+
try:
2284+
decoder.decode(payload, asn1Spec=univ.Sequence())
2285+
except error.PyAsn1Error:
2286+
pass
2287+
else:
2288+
assert False, 'Deeply nested with schema not rejected'
2289+
2290+
21752291
class NonStreamingCompatibilityTestCase(BaseTestCase):
21762292
def setUp(self):
21772293
from pyasn1 import debug

‎tests/codec/cer/test_decoder.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,30 @@ def testDecodeOpenTypesUnknownId(self):
363363
assert s[1][0] == univ.OctetString(hexValue='02010C')
364364

365365

366+
class NestingDepthLimitTestCase(BaseTestCase):
367+
"""Test CER decoder protection against deeply nested structures."""
368+
369+
def testIndefLenNesting(self):
370+
"""Deeply nested indefinite-length SEQUENCEs must raise PyAsn1Error."""
371+
payload = b'\x30\x80' * 200
372+
try:
373+
decoder.decode(payload)
374+
except PyAsn1Error:
375+
pass
376+
else:
377+
assert False, 'Deeply nested indef-length SEQUENCEs not rejected'
378+
379+
def testNoRecursionError(self):
380+
"""Must raise PyAsn1Error, not RecursionError."""
381+
payload = b'\x30\x80' * 50000
382+
try:
383+
decoder.decode(payload)
384+
except PyAsn1Error:
385+
pass
386+
except RecursionError:
387+
assert False, 'Got RecursionError instead of PyAsn1Error'
388+
389+
366390
suite = unittest.TestLoader().loadTestsFromModule(sys.modules[__name__])
367391

368392
if __name__ == '__main__':

‎tests/codec/der/test_decoder.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,48 @@ def testDecodeOpenTypesUnknownId(self):
361361
assert s[1][0] == univ.OctetString(hexValue='02010C')
362362

363363

364+
class NestingDepthLimitTestCase(BaseTestCase):
365+
"""Test DER decoder protection against deeply nested structures."""
366+
367+
def testDefiniteLenNesting(self):
368+
"""Deeply nested definite-length SEQUENCEs must raise PyAsn1Error."""
369+
inner = b'\x05\x00' # NULL
370+
for _ in range(200):
371+
length = len(inner)
372+
if length < 128:
373+
inner = b'\x30' + bytes([length]) + inner
374+
else:
375+
length_bytes = length.to_bytes(
376+
(length.bit_length() + 7) // 8, 'big')
377+
inner = b'\x30' + bytes([0x80 | len(length_bytes)]) + \
378+
length_bytes + inner
379+
try:
380+
decoder.decode(inner)
381+
except PyAsn1Error:
382+
pass
383+
else:
384+
assert False, 'Deeply nested definite-length SEQUENCEs not rejected'
385+
386+
def testNoRecursionError(self):
387+
"""Must raise PyAsn1Error, not RecursionError."""
388+
inner = b'\x05\x00'
389+
for _ in range(200):
390+
length = len(inner)
391+
if length < 128:
392+
inner = b'\x30' + bytes([length]) + inner
393+
else:
394+
length_bytes = length.to_bytes(
395+
(length.bit_length() + 7) // 8, 'big')
396+
inner = b'\x30' + bytes([0x80 | len(length_bytes)]) + \
397+
length_bytes + inner
398+
try:
399+
decoder.decode(inner)
400+
except PyAsn1Error:
401+
pass
402+
except RecursionError:
403+
assert False, 'Got RecursionError instead of PyAsn1Error'
404+
405+
364406
suite = unittest.TestLoader().loadTestsFromModule(sys.modules[__name__])
365407

366408
if __name__ == '__main__':

0 commit comments

Comments
 (0)