@@ -66,6 +66,7 @@ public class X509Factory extends CertificateFactorySpi {
6666 public static final String END_CERT = "-----END CERTIFICATE-----" ;
6767
6868 private static final int ENC_MAX_LENGTH = 4096 * 1024 ; // 4 MB MAX
69+ public static final int BER_ITERATION_COUNT = 128 ; // Limit nested depth
6970
7071 private static final Cache <Object , X509CertImpl > certCache
7172 = Cache .newSoftMemoryCache (750 );
@@ -555,7 +556,7 @@ private static byte[] readOneBlock(InputStream is) throws IOException {
555556 if (c == DerValue .tag_Sequence ) {
556557 ByteArrayOutputStream bout = new ByteArrayOutputStream (2048 );
557558 bout .write (c );
558- readBERInternal (is , bout , c );
559+ readBERInternal (is , bout , c , BER_ITERATION_COUNT );
559560 return bout .toByteArray ();
560561 } else {
561562 try {
@@ -579,12 +580,16 @@ private static byte[] readOneBlock(InputStream is) throws IOException {
579580 * @param is Read from this InputStream
580581 * @param bout Write into this OutputStream
581582 * @param tag Tag already read (-1 mean not read)
583+ * @param depth nesting depth limit
582584 * @return The current tag, used to check EOC in indefinite-length BER
583585 * @throws IOException Any parsing error
584586 */
585587 private static int readBERInternal (InputStream is ,
586- ByteArrayOutputStream bout , int tag ) throws IOException {
588+ ByteArrayOutputStream bout , int tag , int depth ) throws IOException {
587589
590+ if (depth -- == 0 ) {
591+ throw new IOException ("Nesting sequence depth limit reached." );
592+ }
588593 if (tag == -1 ) { // Not read before the call, read now
589594 tag = is .read ();
590595 if (tag == -1 ) {
@@ -610,7 +615,7 @@ private static int readBERInternal(InputStream is,
610615 "Non constructed encoding must have definite length" );
611616 }
612617 while (true ) {
613- int subTag = readBERInternal (is , bout , -1 );
618+ int subTag = readBERInternal (is , bout , -1 , depth );
614619 if (subTag == 0 ) { // EOC, end of indefinite-length section
615620 break ;
616621 }
0 commit comments