View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   https://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.bcel.classfile;
21  
22  import static org.junit.jupiter.api.Assertions.assertThrows;
23  
24  import java.io.ByteArrayOutputStream;
25  import java.io.DataOutputStream;
26  
27  import org.apache.bcel.Const;
28  import org.apache.bcel.generic.ClassGen;
29  import org.junit.jupiter.api.Test;
30  
31  /**
32   * Writer paths must refuse to emit structure counts that overflow their u2/u1 class-file fields instead of silently truncating them
33   * (DataOutputStream.writeShort keeps only the low 16 bits) while still writing every body; the CVE-2022-42920 corruption shape.
34   */
35  class DumpU2OverflowTest {
36  
37      @Test
38      void testDumpRefusesOverflowingInterfaceCount() throws Exception {
39          final JavaClass javaClass = new ClassGen("A", "java.lang.Object", "A.java", Const.ACC_PUBLIC, null).getJavaClass();
40          javaClass.setInterfaces(new int[Const.MAX_SHORT + 1]);
41          try (DataOutputStream dos = new DataOutputStream(new ByteArrayOutputStream())) {
42              assertThrows(ClassFormatException.class, () -> javaClass.dump(dos));
43          }
44      }
45  
46      @Test
47      void testSetExceptionTableRefusesOverflowingCount() {
48          final JavaClass javaClass = new ClassGen("A", "java.lang.Object", "A.java", Const.ACC_PUBLIC, null).getJavaClass();
49          final Code code = new Code(0, 0, 0, 0, new byte[0], null, null, javaClass.getConstantPool());
50          assertThrows(ClassFormatException.class, () -> code.setExceptionTable(new CodeException[Const.MAX_SHORT + 1]));
51      }
52  }