@@ -64,6 +64,7 @@ public class X509Factory extends CertificateFactorySpi {
6464 public static final String END_CERT = "-----END CERTIFICATE-----" ;
6565
6666 private static final int ENC_MAX_LENGTH = 4096 * 1024 ; // 4 MB MAX
67+ public static final int BER_ITERATION_COUNT = 128 ; // Limit nested depth
6768
6869 private static final Cache <Object , X509CertImpl > certCache
6970 = Cache .newSoftMemoryCache (750 );
@@ -553,7 +554,7 @@ private static byte[] readOneBlock(InputStream is) throws IOException {
553554 if (c == DerValue .tag_Sequence ) {
554555 ByteArrayOutputStream bout = new ByteArrayOutputStream (2048 );
555556 bout .write (c );
556- readBERInternal (is , bout , c );
557+ readBERInternal (is , bout , c , BER_ITERATION_COUNT );
557558 return bout .toByteArray ();
558559 } else {
559560 // Read BASE64 encoded data, might skip info at the beginning
@@ -675,12 +676,16 @@ private static void checkHeaderFooter(String header,
675676 * @param is Read from this InputStream
676677 * @param bout Write into this OutputStream
677678 * @param tag Tag already read (-1 mean not read)
679+ * @param depth nesting depth limit
678680 * @return The current tag, used to check EOC in indefinite-length BER
679681 * @throws IOException Any parsing error
680682 */
681683 private static int readBERInternal (InputStream is ,
682- ByteArrayOutputStream bout , int tag ) throws IOException {
684+ ByteArrayOutputStream bout , int tag , int depth ) throws IOException {
683685
686+ if (depth -- == 0 ) {
687+ throw new IOException ("Nesting sequence depth limit reached." );
688+ }
684689 if (tag == -1 ) { // Not read before the call, read now
685690 tag = is .read ();
686691 if (tag == -1 ) {
@@ -706,7 +711,7 @@ private static int readBERInternal(InputStream is,
706711 "Non constructed encoding must have definite length" );
707712 }
708713 while (true ) {
709- int subTag = readBERInternal (is , bout , -1 );
714+ int subTag = readBERInternal (is , bout , -1 , depth );
710715 if (subTag == 0 ) { // EOC, end of indefinite-length section
711716 break ;
712717 }
0 commit comments