diff --git a/pg/src/main/java/org/bouncycastle/gpg/SExpression.java b/pg/src/main/java/org/bouncycastle/gpg/SExpression.java index ee5083ad5e..308ef31b53 100644 --- a/pg/src/main/java/org/bouncycastle/gpg/SExpression.java +++ b/pg/src/main/java/org/bouncycastle/gpg/SExpression.java @@ -104,6 +104,10 @@ private static SExpression parseExpression(InputStream src, SExpression expr, By if (c == ':') { + if (expr == null) + { + throw new IOException("invalid input stream at ':'"); + } try { int len = Integer.parseInt(Strings.fromByteArray(accumulator.toByteArray())); diff --git a/pg/src/test/java/org/bouncycastle/openpgp/test/SExprTest.java b/pg/src/test/java/org/bouncycastle/openpgp/test/SExprTest.java index 03862f62c7..05c11a2580 100644 --- a/pg/src/test/java/org/bouncycastle/openpgp/test/SExprTest.java +++ b/pg/src/test/java/org/bouncycastle/openpgp/test/SExprTest.java @@ -1,15 +1,18 @@ package org.bouncycastle.openpgp.test; import java.io.ByteArrayInputStream; +import java.io.IOException; import java.security.Security; import org.bouncycastle.gpg.SExprParser; +import org.bouncycastle.gpg.SExpression; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPSecretKey; import org.bouncycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; import org.bouncycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBuilder; import org.bouncycastle.openpgp.operator.jcajce.JcePBEProtectionRemoverFactory; +import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.test.SimpleTest; @@ -139,9 +142,25 @@ public String getName() return "SExprTest"; } + private void corruptStreamTest() + throws Exception + { + try + { + SExpression.parse(new ByteArrayInputStream(Strings.toByteArray("2:3abc")), 2); + fail("no exception"); + } + catch (IOException e) + { + isEquals("invalid input stream at ':'", e.getMessage()); + } + } + public void performTest() throws Exception { + corruptStreamTest(); + SExprParser parser = new SExprParser(new JcaPGPDigestCalculatorProviderBuilder().build()); PGPSecretKey k1 = parser.parseSecretKey(new ByteArrayInputStream(key1), new JcePBEProtectionRemoverFactory("fred".toCharArray()), new JcaKeyFingerprintCalculator());