44import java .io .IOException ;
55import java .io .InputStream ;
66
7+ import org .bouncycastle .util .Properties ;
8+
79/**
810 * A parser for ASN.1 streams which also returns, where possible, parsers for the objects it encounters.
911 */
@@ -12,6 +14,8 @@ public class ASN1StreamParser
1214 private final InputStream _in ;
1315 private final int _limit ;
1416 private final byte [][] tmpBuffers ;
17+ private final int level ;
18+ private final int maxLevel ;
1519
1620 public ASN1StreamParser (InputStream in )
1721 {
@@ -33,6 +37,17 @@ public ASN1StreamParser(InputStream in, int limit)
3337 this ._in = in ;
3438 this ._limit = limit ;
3539 this .tmpBuffers = tmpBuffers ;
40+ this .level = 0 ;
41+ this .maxLevel = Properties .asInteger (ASN1InputStream .MAX_CONS_DEPTH , 32 );
42+ }
43+
44+ private ASN1StreamParser (InputStream in , int limit , byte [][] tmpBuffers , int level , int maxLevel )
45+ {
46+ this ._in = in ;
47+ this ._limit = limit ;
48+ this .tmpBuffers = tmpBuffers ;
49+ this .level = level ;
50+ this .maxLevel = maxLevel ;
3651 }
3752
3853 public ASN1Encodable readObject () throws IOException
@@ -48,6 +63,11 @@ public ASN1Encodable readObject() throws IOException
4863
4964 ASN1Encodable implParseObject (int tagHdr ) throws IOException
5065 {
66+ if (this .level == this .maxLevel )
67+ {
68+ throw new IOException ("maximum nested construction level reached - increase " + ASN1InputStream .MAX_CONS_DEPTH + " (currently " + maxLevel + ")" );
69+ }
70+
5171 //
5272 // turn off looking for "00" while we resolve the tag
5373 //
@@ -73,7 +93,7 @@ ASN1Encodable implParseObject(int tagHdr) throws IOException
7393 }
7494
7595 IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream (_in , _limit );
76- ASN1StreamParser sp = new ASN1StreamParser (indIn , _limit , tmpBuffers );
96+ ASN1StreamParser sp = new ASN1StreamParser (indIn , _limit , tmpBuffers , level + 1 , maxLevel );
7797
7898 int tagClass = tagHdr & BERTags .PRIVATE ;
7999 if (0 != tagClass )
@@ -92,7 +112,7 @@ ASN1Encodable implParseObject(int tagHdr) throws IOException
92112 return parseImplicitPrimitive (tagNo , defIn );
93113 }
94114
95- ASN1StreamParser sp = new ASN1StreamParser (defIn , defIn .getLimit (), tmpBuffers );
115+ ASN1StreamParser sp = new ASN1StreamParser (defIn , defIn .getLimit (), tmpBuffers , level + 1 , maxLevel );
96116
97117 int tagClass = tagHdr & BERTags .PRIVATE ;
98118 if (0 != tagClass )
0 commit comments