From 60a3e8874e1646c1198252e531029a6f78ff7a51 Mon Sep 17 00:00:00 2001
From: Richard Atkins <rjatkins359@gmail.com>
Date: Wed, 21 Sep 2022 23:18:58 +1000
Subject: [PATCH] CVE-2022-42920
---
.../java/org/apache/bcel/classfile/ConstantPool.java | 11 +++++++++--
.../java/org/apache/bcel/generic/ConstantPoolGen.java | 11 ++++++++++-
2 files changed, 19 insertions(+), 3 deletions(-)
diff --git a/src/main/java/org/apache/bcel/classfile/ConstantPool.java b/src/main/java/org/apache/bcel/classfile/ConstantPool.java
index c2926c08..b4177771 100644
--- a/src/main/java/org/apache/bcel/classfile/ConstantPool.java
+++ b/src/main/java/org/apache/bcel/classfile/ConstantPool.java
@@ -218,8 +218,15 @@ public class ConstantPool implements Cloneable, Node {
* @throws IOException
*/
public void dump( final DataOutputStream file ) throws IOException {
- file.writeShort(constantPool.length);
- for (int i = 1; i < constantPool.length; i++) {
+ /*
+ * Constants over the size of the constant pool shall not be written out.
+ * This is a redundant measure as the ConstantPoolGen should have already
+ * reported an error back in the situation.
+ */
+ final int size = Math.min(constantPool.length, Const.MAX_CP_ENTRIES);
+
+ file.writeShort(size);
+ for (int i = 1; i < size; i++) {
if (constantPool[i] != null) {
constantPool[i].dump(file);
}
diff --git a/src/main/java/org/apache/bcel/generic/ConstantPoolGen.java b/src/main/java/org/apache/bcel/generic/ConstantPoolGen.java
index 5a09e0d3..ce783549 100644
--- a/src/main/java/org/apache/bcel/generic/ConstantPoolGen.java
+++ b/src/main/java/org/apache/bcel/generic/ConstantPoolGen.java
@@ -95,7 +95,7 @@ public class ConstantPoolGen {
public ConstantPoolGen(final Constant[] cs) {
final StringBuilder sb = new StringBuilder(DEFAULT_BUFFER_SIZE);
- size = Math.max(DEFAULT_BUFFER_SIZE, cs.length + 64);
+ size = Math.min(Math.max(DEFAULT_BUFFER_SIZE, cs.length + 64), Const.MAX_CP_ENTRIES + 1);
constants = new Constant[size];
System.arraycopy(cs, 0, constants, 0, cs.length);
@@ -224,9 +224,18 @@ public class ConstantPoolGen {
/** Resize internal array of constants.
*/
protected void adjustSize() {
+ // 3 extra spaces are needed as some entries may take 3 slots
+ if (index + 3 >= Const.MAX_CP_ENTRIES + 1) {
+ throw new IllegalStateException("The number of constants " + (index + 3)
+ + " is over the size of the constant pool: "
+ + Const.MAX_CP_ENTRIES);
+ }
+
if (index + 3 >= size) {
final Constant[] cs = constants;
size *= 2;
+ // the constant array shall not exceed the size of the constant pool
+ size = Math.min(size, Const.MAX_CP_ENTRIES + 1);
constants = new Constant[size];
System.arraycopy(cs, 0, constants, 0, index);
}
--
2.38.1