bc-java icon indicating copy to clipboard operation
bc-java copied to clipboard

ASN1EncodableVector Thread Safety Regression

Open KyleBS opened this issue 7 years ago • 3 comments

It appears with commit https://github.com/bcgit/bc-java/commit/74b2302d95668af490f312ea9ee2e49a37c955e1 ASN1EncodableVector regressed in terms of thread safety.

To reproduce:

import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.*;

import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.IntStream;

public class TBSCertListThreadSafety {

    public static void main(final String[] args) {
        testNullPointerException();
        testArrayIndexOutOfBoundsException();
    }

    public static void testNullPointerException() {
        System.out.println("=====");
        System.out.println("testNullPointerException");
        System.out.println("=====");

        while (true) {
            try {
                V2TBSCertListGenerator tbsCertListGenerator = new V2TBSCertListGenerator();

                tbsCertListGenerator.setIssuer(new X500Name("CN=foo"));
                tbsCertListGenerator.setSignature(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, DERNull.INSTANCE));
                tbsCertListGenerator.setThisUpdate(new Time(new Date()));
                tbsCertListGenerator.setNextUpdate(new Time(new Date()));

                new ForkJoinPool(2).submit(() ->
                        IntStream.range(0, 1_000_000)
                                .parallel()
                                .forEach(i -> {
                                    ASN1Integer serialNumber = new ASN1Integer(i);
                                    Time revokedAt = new Time(new Date());
                                    int revocationReason = CRLReason.unspecified;
                                    tbsCertListGenerator.addCRLEntry(serialNumber, revokedAt, revocationReason);
                                })).get();

                tbsCertListGenerator.generateTBSCertList()
                        .getEncoded();
            } catch (ExecutionException ex) {
                // Ignore
            } catch (Exception ex) {
                ex.printStackTrace();
                break;
            }
        }
    }

    public static void testArrayIndexOutOfBoundsException() {
        System.out.println("=====");
        System.out.println("testArrayIndexOutOfBoundsException");
        System.out.println("=====");

        while (true) {
            try {
                V2TBSCertListGenerator tbsCertListGenerator = new V2TBSCertListGenerator();

                tbsCertListGenerator.setIssuer(new X500Name("CN=foo"));
                tbsCertListGenerator.setSignature(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, DERNull.INSTANCE));
                tbsCertListGenerator.setThisUpdate(new Time(new Date()));
                tbsCertListGenerator.setNextUpdate(new Time(new Date()));

                new ForkJoinPool(10).submit(() ->
                        IntStream.range(0, 1_000_000)
                                .parallel()
                                .forEach(i -> {
                                    ASN1Integer serialNumber = new ASN1Integer(i);
                                    Time revokedAt = new Time(new Date());
                                    int revocationReason = CRLReason.unspecified;
                                    tbsCertListGenerator.addCRLEntry(serialNumber, revokedAt, revocationReason);
                                })).get();

                tbsCertListGenerator.generateTBSCertList()
                        .getEncoded();
            } catch (ExecutionException ex) {
                ex.printStackTrace();
                break;
            } catch (Exception ex) {
                // Ignore
            }
        }
    }
}

results in:

=====
testNullPointerException
=====
java.lang.NullPointerException
	at org.bouncycastle.asn1.DERSequence.getBodyLength(Unknown Source)
	at org.bouncycastle.asn1.DERSequence.encodedLength(Unknown Source)
	at org.bouncycastle.asn1.DERSequence.encode(Unknown Source)
	at org.bouncycastle.asn1.ASN1OutputStream.writePrimitive(Unknown Source)
	at org.bouncycastle.asn1.ASN1OutputStream.writeObject(Unknown Source)
	at org.bouncycastle.asn1.ASN1Object.encodeTo(Unknown Source)
	at org.bouncycastle.asn1.ASN1Object.getEncoded(Unknown Source)
	at TBSCertListThreadSafety.testNullPointerException(TBSCertListThreadSafety.java:44)
	at TBSCertListThreadSafety.main(TBSCertListThreadSafety.java:15)
=====
testArrayIndexOutOfBoundsException
=====
java.util.concurrent.ExecutionException: java.lang.ArrayIndexOutOfBoundsException
	at java.base/java.util.concurrent.ForkJoinTask.get(ForkJoinTask.java:1006)
	at TBSCertListThreadSafety.testArrayIndexOutOfBoundsException(TBSCertListThreadSafety.java:76)
	at TBSCertListThreadSafety.main(TBSCertListThreadSafety.java:16)
Caused by: java.lang.ArrayIndexOutOfBoundsException
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
	at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
	at java.base/java.util.concurrent.ForkJoinTask.getThrowableException(ForkJoinTask.java:603)
	... 3 more
Caused by: java.lang.ArrayIndexOutOfBoundsException
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
	at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
	at java.base/java.util.concurrent.ForkJoinTask.getThrowableException(ForkJoinTask.java:603)
	at java.base/java.util.concurrent.ForkJoinTask.reportException(ForkJoinTask.java:678)
	at java.base/java.util.concurrent.ForkJoinTask.invoke(ForkJoinTask.java:737)
	at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateParallel(ForEachOps.java:159)
	at java.base/java.util.stream.ForEachOps$ForEachOp$OfInt.evaluateParallel(ForEachOps.java:188)
	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:233)
	at java.base/java.util.stream.IntPipeline.forEach(IntPipeline.java:439)
	at java.base/java.util.stream.IntPipeline$Head.forEach(IntPipeline.java:596)
	at TBSCertListThreadSafety.lambda$testArrayIndexOutOfBoundsException$3(TBSCertListThreadSafety.java:71)
	at java.base/java.util.concurrent.ForkJoinTask$AdaptedRunnableAction.exec(ForkJoinTask.java:1406)
	at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
	at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
	at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
	at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
	at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:177)
Caused by: java.lang.ArrayIndexOutOfBoundsException: arraycopy: last source index 138452 out of bounds for object array[138252]
	at java.base/java.lang.System.arraycopy(Native Method)
	at org.bouncycastle.asn1.ASN1EncodableVector.reallocate(Unknown Source)
	at org.bouncycastle.asn1.ASN1EncodableVector.add(Unknown Source)
	at org.bouncycastle.asn1.x509.V2TBSCertListGenerator.addCRLEntry(Unknown Source)
	at org.bouncycastle.asn1.x509.V2TBSCertListGenerator.addCRLEntry(Unknown Source)
	at org.bouncycastle.asn1.x509.V2TBSCertListGenerator.addCRLEntry(Unknown Source)
	at org.bouncycastle.asn1.x509.V2TBSCertListGenerator.addCRLEntry(Unknown Source)
	at TBSCertListThreadSafety.lambda$testArrayIndexOutOfBoundsException$2(TBSCertListThreadSafety.java:75)
	at java.base/java.util.stream.ForEachOps$ForEachOp$OfInt.accept(ForEachOps.java:204)
	at java.base/java.util.stream.Streams$RangeIntSpliterator.forEachRemaining(Streams.java:104)
	at java.base/java.util.Spliterator$OfInt.forEachRemaining(Spliterator.java:699)
	at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
	at java.base/java.util.stream.ForEachOps$ForEachTask.compute(ForEachOps.java:290)
	at java.base/java.util.concurrent.CountedCompleter.exec(CountedCompleter.java:746)
	... 5 more

KyleBS avatar Oct 16 '19 12:10 KyleBS

Sounds like Hyrum's Law has struck again.

ASN1EncodableVector was only incidentally thread-safe because it used Vector internally. Likewise, the addCRLEntry methods were only incidentally thread-safe. Thread-safety was never advertised and no other code in the library ever assumes it (of these classes).

Thankyou for raising the issue but this is definitely a case where the calling code should be doing the necessary synchronization to avoid concurrently accessing a V2TBSCertListGenerator instance.

peterdettman avatar Oct 16 '19 13:10 peterdettman

Yep, that is more or less the gist of it. The change of behavior leaves me with 2 questions:

  1. As you said, ASN1EncodableVector was only incidentally thread-safe. But it was thread-safe none the less. Are there compelling reasons not to to change the implementation once again to bring back thread-safety?

  2. A Vector is not an ASN.1 type, rather it is a Java construct. While ASN1EncodableVector does not extend Vector, it's name suggests association between the two. And since Vector differentiates via it's thread-safety, there could be a tendency to assume the same for ASN1EncodableVector. Up until this change, this all seemed mostly true. Now that it is not, is there any value in deprecating this class and replacing it with one named in a way to avoid this pitfall?

In general, I can understand that being held to undocumented functionality is not something you generally a desirable position to be in. Ultimately the decision is not mine, I'm just a passerby giving my 2c over something that broke on my end when upgrading.

KyleBS avatar Oct 16 '19 15:10 KyleBS

Arguments about ASN1EncodableVector aside the code should never have been multi-threaded on V2TBSCertListGenerator - to be honest, I think you should be glad it failed now. This is not something we would change back - the class has never claimed to be thread safe.

ghost avatar Oct 16 '19 22:10 ghost