From 25a49a41df8e2be5781399738f3e21a8075d0439 Mon Sep 17 00:00:00 2001 From: David Hook Date: Sun, 12 Jan 2025 10:42:18 +1100 Subject: [PATCH] added check for corrupted stream and escaping NullPointer - relates to github #1888 --- .../org/bouncycastle/gpg/SExpression.java | 4 ++++ .../bouncycastle/openpgp/test/SExprTest.java | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+) 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());